【发布时间】:2022-04-01 00:52:39
【问题描述】:
我正在处理一个 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/controllers/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');
}
}
}
感谢您的 cmets 和替代解决方案..
【问题讨论】:
标签: ruby-on-rails file-upload stimulusjs