gpt4 book ai didi

ruby-on-rails - Rails 3 获取原始发布数据并将其写入 tmp 文件

转载 作者:行者123 更新时间:2023-12-04 04:54:42 25 4
gpt4 key购买 nike

我正在实现 Ajax-Upload用于在我的 Rails 3 应用程序中上传照片。文档说:

  1. For IE6-8, Opera, older versions of other browsers you get the file as you normally do with regular form-base uploads.

  2. For browsers which upload file with progress bar, you will need to get the raw post data and write it to the file.



那么,如何在我的 Controller 中接收原始发布数据并将其写入 tmp 文件,以便我的 Controller 可以处理它? (在我的例子中, Controller 正在做一些图像处理并保存到 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 对象,而是一个包含文件名的字符串。文件的内容存储在请求的正文中(可使用 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

关于ruby-on-rails - Rails 3 获取原始发布数据并将其写入 tmp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com