class Upload < ActiveRecord::Base
belongs_to :user
attr_accessible :picture
has_attached_file :picture, :styles => { :thumb => { :geometry => 'x60',
:quality => 70,
:format => 'JPG'}
}
validates_attachment_presence :picture
validates_attachment_size :picture, :less_than => 5.megabytes
validates_attachment_content_type :picture, :content_type => [ 'image/jpeg', 'image/png', 'image/pjpeg' ]
end
class UploadsController < ApplicationController
def create
p params[:upload]
upload = current_user.uploads.new(params[:upload])
if upload.save
render :json => { :pic_path => upload.picture.url.to_s , :name => upload.picture.instance.attributes["picture_file_name"] }, :content_type => 'text/html'
else
#todo handle error
render :json => { :result => 'error'}, :content_type => 'text/html'
end
end
index.html.erb
<%= form_for current_user.uploads.build, :html => { :id => "fileupload", :multipart => true } do |f| %>
<%= file_field_tag 'upload[picture]', :multiple => true %>
<% end %>
<script>
$(function () {
$('#fileupload').fileupload({
done: function (e, data) {
console.log(data);
},
start: function (e) {
console.log("starting");
},
});
});
</script>
现在一次上传两个文件。 console.log(data); 打印出来的两个对象是正确的,像这样
Object
_bitrateTimer: $.widget._BitrateTimer
_time: 1342493041999
add: function (e, data) {
bitrate: 6035468.671679198
bitrateInterval: 500
blob: null
cache: false
contentType: false
data: FormData
disabled: false
done: function (e, data) {
dropZone: e.fn.e.init[1]
fileInput: e.fn.e.init[1]
files: Array[1]
forceIframeTransport: false
form: e.fn.e.init[1]
formData: function (form) {
jqXHR: Object
lengthComputable: true
loaded: 301019
multipart: true
namespace: "fileupload"
originalFiles: Array[2]
paramName: Array[1]
processData: false
progressInterval: 100
recalculateProgress: true
replaceFileInput: true
result: "{"pic_path":"/system/uploads/pictures/000/000/032/original/562c11dfa9ec8a131c35c958f703918fa0ecc05f.jpg?1342493042","name":"562c11dfa9ec8a131c35c958f703918fa0ecc05f.jpg"}"
sequentialUploads: false
singleFileUploads: true
start: function (e) {
submit: function () {
textStatus: "success"
total: 301019
type: "POST"
uploadedBytes: 0
url: "http://localhost:3000/uploads"
xhr: function () {
__proto__: Object
但是一访问 data.result.name 就是 undefined 而且 firebug 上 network 上看到的两次 post 返回的 json 都是一样的,都是第二个文件的信息。