ruby-on-rails – Rails 3获取原始帖子数据并将其写入tmp文件
发布时间:2020-12-16 20:05:33 所属栏目:百科 来源:网络整理
导读:我正在努力实现 Ajax-Upload,用于在我的Rails 3应用程序中上传照片.文件说: For IE6-8,Opera,older versions of other browsers you get the file as you normally do with regular form-base uploads. For browsers which upload file with progress bar,y
我正在努力实现
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |