jquery fileupload 上传

参考链接:https://github.com/carrierwaveuploader/carrierwave

使用 jquery.fileupload.js 上传图片

  1. gem 'carrierwave' 和 gem 'mini_magick'
  2. bundle
  3. 执行rails generate uploader image 会生成app/uploaders/image_uploader.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/"
end
process resize_to_fit: [800, 800]
version :small do
process resize_to_fit: [200, 200]
end
end
  1. controller中 action 可以使用
    1
    2
    3
    4
    uploader = ImageUploader.new
    uploader.store!(my_file)
    uploader.url # => '/url/to/my_file.png' # size: 800x600
    uploader.thumb.url # => '/url/to/thumb_my_file.png' # size: 200x200

我的场景是,在页面用jquery uploader 到后面action上传图片,回传image_url 到页面,页面点击保存的时候再保存到相关的数据库表。

见截图:

1
2
3
4
5
6
7
8
9
class ImagesController < ApplicationController
def create
uploader = ImageUploader.new
uploader.store!(params['picture-upload'])
render json: {image_url: uploader.small.url}
end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function pictureUpload(prize){
$(".picture-upload").click();
$".picture-upload").fileupload({
type:'POST',
url:'/images',
dataType: 'json',
singleFileUploads: true,
maxFileSize: 2000000,
start: function (e) {
$(".progress-upload").removeClass('hide');
$(".upload-button i").addClass('hide');
$(".upload-button span").addClass('hide');
},
progressall: function(e, data){
var progress = parseInt(data.loaded/data.total * 100, 10);
$(".progress-upload .bar").css('width',progress + '%');
},
done: function(e, data){
$(".edit-button .prize-picture").attr('src',data.result.image_url);
$(".upload-button").remove();
$(".edit-button").removeClass('hide');
},
});
}