ruby-on-rails - 使用刺激 javascript(ruby on rails)选择后立即预览多个图像
问题描述
我正在处理一个rails项目,我试图上传多个图像并在图像选择后立即预览它们。我正在使用刺激,ruby on rails,js6
HTML是用于创建新产品的表单-我也在使用cloudinary-上传多张图片和simpleformfor
app/views/products/_form.html.erb
<%= simple_form_for product do |m| %>
<div class="d-flex justify-content-between" data-controller="upload">
<%= m.input :photos, as: :file, input_html: { multiple: true, class: 'hidden', id: 'photo-input',
data: {action: 'change->upload#displayPreview'} },
label_html: { class: 'upload-photo'}, label: ':camera: Upload a photo' %>
<% if @product.photos.attached? %>
<% @product.photos.each do |photo| %>
<%= cl_image_tag photo.key, height: 100, width: 200, crop: :fill, data: { target: 'upload.image'} %>
<% end %>
<% end %>
</div>
<%= m.button :submit, class: 'btn-primary' %>
<% end %>
1 张图片的 HTML 表单代码如下
<div data-controller="upload">
<label class="file optional upload-photo" for="photo-input">Upload photo</label>
<input class="form-control-file file optional hidden" id="photo-input" data-action="change->upload#displayPreview" type="file" name="product[photos][]">
<%= cl_image_tag "", height: 100, width: 200, crop: :fill, data: { 'upload-target': 'image', 'upload-index-value': 0 } %>
</div>
</div>
如果表单仅适用于 1 张图片,则 1 张图片的代码如下,并且工作正常,但我将如何转换以下代码以适应多张图片上传?我使用 for 循环和 this.imageTargets.forEach((element) => {.. 甚至索引尝试了几件事,但无济于事..
javascript/控制器/upload_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ['image']
displayPreview(event) {
const input = event.target
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = (event) => {
this.imageTarget.src = event.currentTarget.result;
}
reader.readAsDataURL(input.files[0])
this.imageTarget.classList.remove('hidden');
}
}
}
感谢您的评论和替代解决方案..
解决方案
推荐阅读
- postgresql - 在 SQL Server 导入导出工具中连接到 PostgreSQL 数据源
- python - Django 管理面板、关系和只读字段
- sqlite - 我有 2 个关于使用 2 个表的 sqlite3 查询的问题
- javascript - 角度7中的虚拟滚动,拖放
- ios - 在视图控制器与搜索控制器搜索栏之间导航隐藏和显示有 ui 故障
- mongodb - 当我在 mongo 中显示数据库时,为什么我创建的数据库不显示?
- java - Vowpal Wabbit 的工作流程
- c# - 如何同时删除文件夹中的所有相关文件和数据库中的引用?
- tensorflow - 如何在 TF 2.0 数据集映射步骤中从张量中获取和使用值?
- java - 在集成测试中模拟嵌入对象