Friday, August 12, 2016

Image preview before upload rails

app/model/image.rb

class Image < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
  IMAGE_STYLES = {:large => "800x>", :intermediate => "600x>", :medium => "300x>", :thumb => "190x>", :small => "60x>" }
  has_attached_file :image, { :styles => Image::IMAGE_STYLES,
                                            :convert_options => {:large => '-strip -quality 85',
                                                                              :intermediate => '-strip -quality 85',
                                                                              :medium => '-strip -quality 85',
                                                                              :thumb =>  '-strip -quality 85',
                                                                              :small => '-strip -quality 85',
                                                                            },
                              }.merge(IMAGE_PATH).merge(S3_STORAGE)
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end


app/controllers/images_controller.rb

class ImagesController < ApplicationController
  def new
    @image = Image.new
  end
end


app/views/images/new.html.haml

= form_for @image do |f|
  = f.file_field :image, :class => "gui-file images_upload"
  = f.submit

app/assets/javascrips/application.js

//= require 'common'

app/assets/javascrips/common.js

function readURL(input) {
  if (input.files && input.files[0]) {
    console.log(input.files);
    for (var i = 0, f; f = input.files[i]; i++) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $(input).next().next(".previewImages").html('')
      }
      reader.readAsDataURL(f);
    }
  }
}
------------------------------------------------------------------------------------------------------------------
$(document).on("change", ".images_upload", function(){
  readURL(this);
});




No comments:

Post a Comment