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

Access files on AWS S3 bucket using aws-sdk-s3 with Rails 6

This is a quick post to share few easy methods to access files on AWS S3. The below custom utility methods uses  aws-sdk-s3 Firstly lets define a constant to access files on S3 -  ##to manage S3 Resources S3 = Aws::S3::Resource.new( region: "YOUR-REGION", access_key_id: "YOUR-AWS-KEY", secret_access_key: "YOUR-AWS-SECRET") ##to query S3 S3_client = Aws::S3::Client.new( access_key_id: configatron.aws.s3.credentials.access_key_id, secret_access_key: configatron.aws.s3.credentials.secret_access_key, region: configatron.aws.s3.region ) Now, lets use the S3 OBJECT to access files in different ways -  1. Get all files in a S3 FOLDER     ##this gives a array of file paths present in the folder specified by prefix attribute          s3objects = S3.bucket("my-output-bucket").objects({prefix: "/inputs/any-random-user-folder"}).collect(&:key) ##you can also delete the file if found ...

Setting Axios to put/post dynamically

 Let me avoid wasting more time and quickly jump on the problem statement. What is the problem statement -  - I want to use the same React component both for Create/Update. How I achieved it -  - Firstly for new object, it worked smoothly and I wanted to reuse the same component again for edit/update too. - I sent the existing values as props and saved them into the corresponding states. - I reused the existing method ( axios server call ) so that it dynamically POST/PUT as needed.This is show below -         //this method calls post/put dynamically - simple code here..no rocket science methodCall = () => { const { Id, editable, details } = this.state; //check if new or existing record if (editable) { return API.put(`/post/${Id}`, details); } else { return API.post("/post", details); } }; //call this method onClick/onSubmit - as you want to handleSubmit = (event) => { event.preventDefault(); ...

So easy to install ruby on rails on ubuntu 12.04/centos 6 and start development

Its easy to start development on ubuntu/centos using vmware and start development.i will start the code on certain assumptions : you know ruby on rails you are aware of how to make use of google(in case u are stuck and want to explore more without spoon feeding) LAST BUT NOT LEAST---you love coding short preview of sequence you need to follow:  START -> get vmware -> get ubuntu/centos -> get rvm -> get ruby -> get rails----END--THAT'S IT Lets start and finish this quickly using below mentioned steps: install vmware player if you are using windows/mcintosh from https://my.vmware.com/web/vmware/downloads  NOW.vmware player need image file of the operating system you want,so hit the url and get centos at http://vault.centos.org/6.2/isos/ OR ubuntu at http://www.ubuntu.com/download/desktop ONCE both vmware player and ubuntu/centos are downloaded,follow the steps to first install vmware(very simple) and mounting ubu...