在控制台中以 Rails 方式上传文件如下所示:
Started POST "/onboard/add_doc" for 2600:1700:ba00:3970:1900:ab4c:b842:8b5c at 2021-03-13 12:42:47 -0800
Processing by Users::DocsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "doc"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x00007fe0fef3de78 u/tempfile=#<Tempfile:/var/folders/hj/g_90jx_n7s58m73qlf9h0c4w0000gn/T/RackMultipart20210313-97062-1pd54fh.jpg>, u/original_filename="Gil-Next-Door-Gil-and-Wolly.jpg", u/content_type="image/jpeg", u/headers="Content-Disposition: form-data; name=\"doc[image]\"; filename=\"Gil-Next-Door-Gil-and-Wolly.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Upload"}
但是我没有那样做。一个名为 Uppy 的 js 库处理文件选择和上传,并将 JSON 插入隐藏的表单字段。提交此表单时,它不会自动转换为ActionDispatch::Http::UploadedFile
对象。我不完全确定为什么,所以我在控制器中处理它:
def create
image = params.require(:doc).fetch(:image)
file = StringIO.new(image)
lockbox = Lockbox.new(key: Lockbox.attribute_key(table: "docs", attribute: "image"))
encrypted_image = lockbox.encrypt_io(file)
@doc = Doc.new(user_id: current_user.id, image: encrypted_image, mime_type: mime_type)
@doc.save
end
控制台输出如下所示:
Processing by Users::IdDocsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "doc"=>{"image"=>"{\"id\":\"6536f20f163a67f5b432d250351eac7c.jpg\",\"storage\":\"cache\",\"metadata\":{\"size\":55368,\"filename\":\"cam-1615814031784.jpg\",\"mime_type\":\"image/jpeg\"}}"}, "commit"=>"Upload"}
该输出很好(我认为),但文件在上传之前没有正确加密。当我查看它们时,我得到了空白的白色方块,并且密码箱需要一个ActionDispatch::Http::UploadedFile
对象。我的uploaded_file
定义是否遗漏了什么?如何访问uploaded_file
属性,例如headers
确保其正确提交?