如何使用Rails Active Storage在视图中显示临时文件图像

问题描述 投票:1回答:1

在我的Rails 6应用程序中,我使用活动存储将文件上传到cloudinary。我有一个功能,可以在提交之前预览表单。这还要求我在提交之前预览仍然是临时文件的上传图像。我正在create.html.erb中设置预览。这是我尝试在create.html.erb中预览图像临时文件的方式,但是它不起作用。

    <%= image_tag params[:company][:logo].path %>

这是我的公司模样

class Company < ApplicationRecord
  belongs_to :user
  has_one_attached :logo
end

如何在视图中显示临时图像?

ruby-on-rails ruby cloudinary rails-activestorage ruby-on-rails-6
1个回答
0
投票

我认为,如果您尚未提交表格,则尚未上传。

在这种情况下,您可以显示仍在浏览器中的图像。

将会是这样:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
    }
    
    reader.readAsDataURL(input.files[0]); // convert to base64 string
  }
}

$("#imgInp").change(function() {
  readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" />
</form>

查看此问题以查看更多详细信息:Preview an image before it is uploaded

© www.soinside.com 2019 - 2024. All rights reserved.