Install and use jquery-file-upload step by step
1. Install gem
Add the gem of jquery-fileupload-rails and paperclip to gemfile:
gem "jquery-fileupload-rails"gem 'paperclip'
2. Add in APP/assets/application. js
//= require jquery-fileupload
3. Add in APP/assets/stylesheets/application.css
*= require jquery.fileupload-ui
4. Create a picture data table
rails g model Picture avatar:attachmentrake db:migrate
The Avatar attribute of the pictures table indicates the object to be uploaded.
Modify the contents of picture. RB:
In the model, use the class method has_attached_file to specify that the file object is Avatar and define the to_json_picture method. This method converts the picture object into a hash, the interaction between jquery-fileupload and server is converted to JSON data.
5. Create a view
Create an upload interface index.html. ERB only. To customize your own view, you only need to change form_for picture. New and F. file_field: avatar to your own model. You can copy-paste other content directly.
<div class="container"> 6. Create a controller
rails g controller pictures index create destroy
class PicturesController < ApplicationController def index @pictures = Picture.all respond_to do |format| format.html # index.html.erb format.json { render json: @pictures.map{|picuture| picuture.to_json_picture } } end end # POST /picture # POST /picture.json def create @picture = Picture.new(params[:picture]) respond_to do |format| if @picture.save format.html { render :json => [@picture.to_json_picture].to_json, :content_type => 'text/html', :layout => false } format.json { render json: {files: [@picture.to_json_picture]}, status: :created, location: @picture } else format.html { render action: "new" } format.json { render json: @picture.errors, status: :unprocessable_entity } end end end # DELETE /picture/1 # DELETE /picture/1.json def destroy @picture = Picture.find(params[:id]) @picture.destroy respond_to do |format| format.html { redirect_to picture_url } format.json { head :no_content } end endend
7.
This is the final result. If you want to achieve the beautiful results in jqeury-fileupload demo, for example, you need to use Twitter-Bootstrap or write CSS on your own.