Rails 从上传的文件中读取 base64 字符串而不保存文件

Rails read base64 string from uploaded file without saving the file

对于我在 Rails 项目上的 Ruby,我有一个允许用户上传文件的表单(例如,图像的 jpg 文件)。我不想将该图像另存为我应用程序中任何位置的文件。但是,我想提取上传图片的 base64 字符串。

所以对于我的表格(我使用的是 Slim)

 = form_tag somepath, method: :post, remote: true do
   .form-group
        = label_tag :file
        = file_field_tag :file

然后在控制器中我有

def allowed_params
  params.permit([:file])
end

但是,在使用 UI 上传文件 photo.jpg 后执行 File.open(allowed_params[:file], 'rb'){|f| f.read} 时,出现错误 Errno::ENOENT Exception: No such file or directory @ rb_sysopen - C:\fakepath\photo.jpg

我尝试了 Base64.encode64(File.open('someotherfile.jpg').read),其中 someotherfile.jpg 是一个文件,我知道它在哪里并且有效,并且运行良好。

有什么建议吗?提前致谢。

你能确定你使用的是多部分表单吗?您可以通过在 form_tag 帮助程序(例如 form_tag somepath, method: :post, remote: true, multipart: true)中设置 multipart: true 来做到这一点。那么你应该能够通过allowed_params[:file].read访问控制器中的内容。