首页 > 解决方案 > 使用刺激 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');
    }
  }
}

感谢您的评论和替代解决方案..

标签: ruby-on-railsfile-uploadstimulusjs

解决方案


推荐阅读