Skip to main content

Show image preview on upload -RAILS

i have been using Ruby on Rails (versions 2/3/4) and loved it because its so quick and saves the time to build website that normally require an year.
Recently i implemented uploading videos/music/images using paperclip,ffmpeg-paperclip and delayed_paperclip.i wanted to upload multiple images where i can see the uploaded images before submitting.So here is the code using paperclip and jquery where you can preview your uploaded images in a list format + a customised upload button(see below) instead of the traditional browse button for uploading files.
i am using bootstrap 3 and FontAwesome(for upload button icon)


Description:-

  1. In the form,i have input button of type file and added a style to give it a look as shown above which works good and responsively.
  2.  In the jquery,it detects for a change in upload button using change event listener and get all the uploaded file and lists it to the  div with id = list using li
  3. The code also has validations to show errors if non-image file is attached,file more than 1mb is attached and more than 5 files (for multiple uploads at once)
  4. Optional--you can also add a remove button on each uploaded image preview so that you can also remove the uploaded images and attach a new one instantly by using the $("id").remove
Lets start with the code
 
====================_form.html.erb

 <%= form_for(@user,:html=>{:multipart => true,:remote=>true,:class=>"form-horizontal",:role=>"form"}) do |f |%>

    <div class="col-lg-12">
      <a href="javascript:void(0);" class="upload btn">
        <i class="fa fa-upload fa-lg" style="padding-right: 5px"></i>
        Upload picture
        <%= f.file_field :avatar,:id=>"user_avatar",:multiple=>"true",:class=>"opacity"%></a>
        <span class="text-info"><small style="margin-left: 13px;">You can select 5 images at a time</small></span>

    <!-- show error here ->
      <p id="show_error" class=" col-md-offset-0" style="color: red; display: none;"></p>
  </div>

<!-- show uploaded images in list using col-lg-12 -->
    <div class="row text-success form-group">
    <ul id="list_images_places" style="list-style: none outside none;">

    </ul>
    </div>
<%end%>

=================my javascript:

$("#user_avatar").change(function(evt){

//remove the image onchange always
$('#list_images_places li').remove();
$("#show_error").html(" ").hide();
//check file type
var ext = $('#user_avatar').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg','tiff','bmp']) == -1) {
    $("#show_error").html("This is not an image file").show();
    //show no files selected
    $('#user_avatar').val("");
    return false;
}
     //get the file size and file type from file input field
       // var fsize = $('#i_file')[0].files[0].size;
        //var ftype = $('#i_file')[0].files[0].type;
        //var fname = $('#i_file')[0].files[0].name;
        //1048576--1MB
//check file size
   var file = $('#user_avatar')[0].files[0];
  if (file.size && file.size > 1048576) {
              $("#show_error").html("File size must be within 1 Mb or below").show();
                //show no files selected
              $('#user_avatar').val("");
              return false;  
            }

//check only 4 files uploaded at a time
var numFiles = $('#user_avatar')[0].files.length;
if (numFiles > 5){
     $("#show_error").html("Only 5 images can be uploaded at a time").show();
                //show no files selected
              $('#user_avatar').val("");
              return false;

}

<1--  code the add uplaoded images and show the listing in thumbnail format-->
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var li = document.createElement('li');
          li.innerHTML = ['<div style="width:100px !important;float:left !important;margin:10px;"><img class="thumb img-responsive" src="', e.target.result, '" title="', escape(theFile.name), '"/></div>'].join('');
                    document.getElementById('list_images_places').insertBefore(li, null);

        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  });


=================CSS style:

    .upload{
       padding: 8px 10px;
       position: relative;
       border-radius: 5px;
       width: auto !important;
    }
    .upload input[type="file"]{
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    }
    .opacity{
     -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
      filter: alpha(opacity=0);
     -moz-opacity: 0;
     -khtml-opacity: 0;
     opacity: 0;
    }
    /*bootstrap*/
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: whiteSmoke;
border: 1px solid #E3E3E3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
    float: left;
  }


   
this is how it looks in action:

 The above code can be customized in the way you want and can be used with cross browsers as well.


Comments

Popular posts from this blog

Using Geocoder to get street name,state,city,country etc in Your Rails app

Recently i implemented Google map for one of the module where User will enter his location/address and other relevant geo-details should get autopopulated.Well,This was posible because of   Geocoder  and by using it you can get every small details such as postalcode,country code,zipcode,street name,state name,state code,latitude,longitude(and more) ready in your hands easily.Its really awesome. I have used to it get all relevant information about the location that the user enter using Geocomplete ,another awesome autocomplete library to get locations. Suppose you have a users table and also few columns such as longitude,latitude,state,postal code,street name,address,country  and want to autopopulate other fields just by using address entered by the user then you are reading the right blog,So its easy,let me show you how. User will enter address using Geocomplete and store that address in address column in users/locations table Then,use Geocoder to fetch other geo informations

Adding Emoji icons to Rails application

Its very easy to add emoji icons/images to your rails application. It seems complex but its all easy using javascript.The steps can be simplified as shown below:- add the javascript(download jemotion ) include it in your view file(where you want :) to be shown as this -----------------------> thats it....done first you need to add this wonderful js which works really great and nice from home page . We are interested in only the js and emotions folder(containing the smileys/GIF images). once you download just include it in your view file and copy/dump the emotions folder(containing images) to app/assets/images for RAILS 3+. as i did where i want the users to view their comments after they submit their comment. You also need to give a unique id to make  the js understand where it needs to convert your symbols to icons.see below code and hope you will understand how to use it. Keep in mind two thing:- dont forget to gi

Convert videos using ffmpeg by ffmpeg_paperclip-Rails

Recently i implemented video uploads at S3 using ffmpeg-paperclip and ffmpeg where my uploaded videos get converted into mp4,webm and ogg(most required formats) along with 2 screenshots(with diff sizes) and stored at S3. its so wonderful in many ways:- your uploaded videos get converted into required formats(compatible on all browsers) before saving using ffmpeg through ffmpeg-paperclip moreover,you will also get screenshot(2 different images)of every video uploaded + AMAZON S3( you can even store locally,refer Paperclip ) if you want the background job to process video conversion then,use delayed_paperclip  i will show you how you can convert your uploaded videos into required formats and why we need to convert ....well refer  this .Before starting make sure that you have ffpmeg installed with all libraries needed,so click the above link instead of searching for how to install ffmpeg and install it( will take around 30mins.but its worthy ). Here i am using mediaelement.