【问题标题】:Image preview in ruby on rails using vanilla javascript [duplicate]使用香草javascript在ruby on rails中预览图像[重复]
【发布时间】:2021-09-29 21:18:16
【问题描述】:

所以我在我的 rails 应用程序上传期间构建了一个图像预览器,我偶然发现了this solution。如果我理解正确,文件输入中有一个 onchange 侦听器,它会触发将图像标签的 src 更改为上传文件的 URL。这是我的版本:

function readURL(input) {
    console.log(input.files)
    if (input.files && input.files[0]) {     
        var reader = new FileReader();          
        
        reader.onload = function(e) {       
            let imagePreviewContainer = document.getElementById('image-preview-container');
            let previewContent = "";
        
            for (let i = 0; i < e.target.result.length; i++) {
                previewContent += `<img src="${e.target.result[i]}">`
            }
        console.log(previewContent);
        imagePreviewContainer.innerHTML = previewContent;
      }
       
    reader.readAsDataURL(input.files[0]); // convert to base64 string   
    } 
}

let imageFileField = document.getElementById('image-input');
imageFileField.addEventListener('change', () => {
    console.log("upload detected");   
    console.log(this);
    readURL(this);
});

这是 .html.erb 文件:

    <div class="modal fade" id="create-item-modal" tabindex="-1" aria-labelledby="create-item-modalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="create-item-modalLabel">New listing</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <%= form_with scope: :item, url: items_path(current_user.id), local: true do |f| %>
              <div class="field">
                <%= f.label :name, "Item name" %><br />
                <%= f.text_field :name, class: "form-control", autofocus: true %>
              </div>

              <div class="field">
                <%= f.label :images %><br />
                <%= f.file_field :images, id: "image-input", multiple: true %>
              </div>

              <div id="image-preview-contaier"></div>

              <div class="field">
                <%= f.label :description %><br />
                <%= f.text_area :description, class: "form-control", size: "30x10", autofocus: true %>
              </div>
              
              <%= f.hidden_field :status, value: "open" %>
              <%= f.hidden_field :user_id, value: current_user.id %>
              <%= hidden_field_tag(:user_id, current_user.id) %>
            
              <div class="modal-footer">
                <%= f.submit "Create listing", class: "btn btn-primary" %>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              </div>
            <% end %>
          </div>
          
        </div>
      </div>
    </div>

通过这些修改,我在 console.log(this) 中得到一个空对象,因此 readURL 函数并没有真正得到正确的参数。似乎是什么问题?提前致谢!

【问题讨论】:

  • 最好使用URL.createOjectURL(file)

标签: javascript jquery ruby-on-rails


【解决方案1】:

这是我为修复它所做的。

function readURL(input) {
    if (input.files && input.files[0]) {
        for (let i = 0; i < input.files.length; i++) {
            var reader = new FileReader();
            var img = document.createElement('img');
            img.setAttribute("style","width:100px; height:auto;");
    
            reader.addEventListener("load", function () {
                var image = new Image();
                image.width = 100;
                image.title = input.name;
                image.src = this.result;
                imagePreviewContainer.appendChild(image);
              }, false);

            reader.readAsDataURL(input.files[i]); // convert to base64 string
            
        }
    } 
}

const imagePreviewContainer = document.getElementById('image-preview-container');
const imageFileField = document.getElementById('image-input');
imageFileField.addEventListener('change', function() {  
    readURL(this);
});

我查看了 FileReader 文档并了解了如何实现负载侦听器。另外,我将 imagePreviewContainer 的内容更改为 innerHTML 以使用 createElement 方法动态创建 img 标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 2019-05-07
    • 2012-01-21
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多