Skip to content

Instantly share code, notes, and snippets.

@abelorian
Last active October 30, 2018 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelorian/8caf0575344e37f13b46b3c875058cef to your computer and use it in GitHub Desktop.
Save abelorian/8caf0575344e37f13b46b3c875058cef to your computer and use it in GitHub Desktop.
Preview in upload file with javascript and ruby on rails
<div class="control-group">
<%= form.label :plan_image %>
<div class="controls">
<div id="plan_image_preview_block" class="imageUpload imageUpload-16_9" style="<%= 'display: none;'.html_safe if @plan.try(:plan_image).try(:url).nil? %>">
<div class="imageUpload-media" id="plan_image_preview" style="background-image: url(<%= @plan.try(:plan_image).try(:url) || '' %>);"></div>
</div>
<div class="input-file-wrapper">
<a class="btn btn--s btn--secondary">
<% if @plan.plan_image.present? && @plan.plan_image.file.exists? %>
<i class="icon icon-16 flaticon stroke photo-1"></i> Change image
<% else %>
<i class="icon icon-16 flaticon stroke upload-1"></i> Upload a file
<% end %>
</a>
<%= form.file_field :plan_image %>
</div>
<p class="help-block">
Resolution: 1280x720 &#8212; Aspect Ratio: 16:9
</p>
</div>
</div>
<script>
$(document).ready(function(){
$('input[type="file"]').change(function(){
var image = window.URL.createObjectURL(this.files[0]);
$("#plan_image_preview").css("background-image", "url(" + image + ")");
$("#plan_image_preview_block").show();
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment