我正在尝试结合ng-文件上传 and 载波上传多个文件,但服务器端的控制器只接收一个文件(所选文件的最后一项)。
客户端 (参考 https://github.com/danialfarid/ng-file-upload#-usage)
html
<button type="file" ng-model="files" ngf-select ngf-multiple="true">Upload</button>
js
var upload = function (files, content) {
return Upload.upload({
url: 'MY_CONTROLLER_URL',
file: files, // files is an array of multiple files
fields: { 'MY_KEY': 'MY_CONTENT' }
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('files ' + config.file.name + ' uploaded. Response: ' + data);
}).error(function (data, status, headers, config) {
console.log('error status: ' + status);
});
};
console.log(files)
prints 数组[文件,文件,...](浏览器:FireFox)。所以在客户端它确实获取了选定的文件。上GitHub页的ng-文件上传说它支持文件数组html5
.
服务器端 (参考 https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads)
posts_controller.rb
def create
@post = Post.new(post_params)
@post.attaches = params[:file]
@post.save
render json: @post
end
private
def post_params
params.require(:post).permit(:content, :file)
end
where @post.attaches
是帖子的附件,params[:file]
由客户端发送file
参数输入Upload.upload
.
我想将文件数组存储到@post.attaches
, but params[:file]
仅包含所选文件中的一个文件。puts params[:file]
prints:
#<ActionDispatch::Http::UploadedFile:0x007fddd1550300 @tempfile=#<Tempfile:/tmp/RackMultipart20150812-2754-vchvln.jpg>, @original_filename="Black-Metal-Gear-Rising-Wallpaper.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"Black-Metal-Gear-Rising-Wallpaper.jpg\"\r\nContent-Type: image/jpeg\r\n">
这表明只有一个文件params[:file]
。不知道这个参数的使用有没有什么问题。
我该如何解决这个问题?
这是我的post.rb
模型和attach_uploader.rb
(由...制作载波)供需要时参考:
post.rb
class Post < ActiveRecord::Base
mount_uploaders :attaches, AttachUploader
end
附加上传器.rb
class AttachUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
and @post.attaches
数据库中的列posts
添加者为
rails g migration add_attaches_to_posts attaches:json