1

In my rails 6 application, I use active storage to upload files to cloudinary. I have a feature where I will like to preview a form before submitting it. This also requires that I preview an uploaded image that is still a tempfile before submitting it. I am setting up the preview in create.html.erb . This is how I have attempted to preview the image tempfile in create.html.erb but it is not working.

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

This is how my company model looks like

class Company < ApplicationRecord
  belongs_to :user
  has_one_attached :logo
end

How do I display a temp image in my views ?

Hakeem Baba
  • 393
  • 5
  • 22

1 Answers1

1

I think if you haven't submitted the form it hasn't been uploaded yet.

In this case, you can show the image that is still in the browser.

It would be something like this:

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>

Take a look at this question to see more details: Preview an image before it is uploaded.

Matheus
  • 920
  • 12
  • 25
  • thanks but i am looking for a non-javascript solution. I prefer to use just rails or ruby – Hakeem Baba Apr 11 '20 at 15:26
  • Has the form been submitted? If not, it is impossible to do it without JavaScript. – Matheus Apr 11 '20 at 19:52
  • this solution only works in new.html.erb when the user uploads the image but i actually want to preview the image in create.html.erb. I explain the situation here https://stackoverflow.com/questions/61443593/how-to-preview-an-image-that-was-attached-on-a-different-page-rails-and-active – Hakeem Baba Apr 26 '20 at 22:29