我正在努力实现
Ajax-Upload,用于在我的Rails 3应用程序中上传照片.文件说:
那么,如何在我的控制器中收到原始的post数据并将其写入一个tmp文件,这样我的控制器就可以处理它了? (在我的情况下,控制器正在做一些图像操作并保存到S3.)
一些额外的信息:
正如我现在配置的那样,这个帖子是传递这些参数的:
Parameters: {"authenticity_token"=>"...","qqfile"=>"IMG_0064.jpg"}
…和CREATE操作如下所示:
def create @attachment = Attachment.new @attachment.user = current_user @attachment.file = params[:qqfile] if @attachment.save! respond_to do |format| format.js { render :text => '{"success":true}' } end end end
…但是我得到这个错误:
ActiveRecord::RecordInvalid (Validation Failed: File file name must be set.): app/controllers/attachments_controller.rb:7:in `create'
解决方法
那是因为params [:qqfile]不是一个UploadedFile对象,而是包含文件名的String.文件的内容存储在请求的正文中(可以使用request.body.read访问).当然,你不能忘记向后的兼容性,所以你还必须支持UploadedFile.
所以在你可以统一的方式处理这个文件之前,你必须抓住这两种情况:
def create ajax_upload = params[:qqfile].is_a?(String) filename = ajax_upload ? params[:qqfile] : params[:qqfile].original_filename extension = filename.split('.').last # Creating a temp file tmp_file = "#{Rails.root}/tmp/uploaded.#{extension}" id = 0 while File.exists?(tmp_file) do tmp_file = "#{Rails.root}/tmp/uploaded-#{id}.#{extension}" id += 1 end # Save to temp file File.open(tmp_file,'wb') do |f| if ajax_upload f.write request.body.read else f.write params[:qqfile].read end end # Now you can do your own stuff end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。