我有一个 Rails 4 应用程序,我在其中使用 jQuery 文件上传向 Carrierwave 发送请求。我的代码如下所示:
<input name='photo[image]' type='file' data-url='photos/create' multiple="true" class='fileupload'/>
和我的jquery:
$('.fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
alert(file.name);
});
}
});
以及我在照片 Controller 中的创建操作:
def create
@photo = Photo.new(photo_params)
respond_to do |format|
if @photo.save
format.json { render json: @photo }
else
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
private
def photo_params
params.require(:photo).permit!
end
和我的照片模型:
class Photo < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
当我创建照片时,Carrierwave 正确创建图像(在 public/uploads 目录中),但由于某种原因我的 jQuery 出现错误:
Uncaught TypeError: Cannot read property 'length' of undefined
不知道是什么原因造成的?
最佳答案
我应该将此作为评论留下,但我没有足够的声誉,所以我很抱歉。
我认为你只需要使用 data.files 而不是 data.result.files
像这样
$('.fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.files, function (index, file) {
alert(file.name);
});
}
});
关于javascript - 文件上传无照片参数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24392209/