2017-06-22 73 views
0

我有一个Base64编码的图片进入我的应用程序。我想在其他地方重新发布该映像,但它将内容类型设置为目标上的多部分/表单数据。我如何上传这张图片?Rails的帖子图片

file_name = permitted_params[:file_name] 
file_contents = permitted_params[:file_contents] 

file = Tempfile.new(file_name) 
file.binmode 
file.write(Base64.decode64(file_contents)) 
file.rewind() 

raw_response = RestClient.put(
    url, 
    { 'upload' => file, :content_type => 'image/jpeg' }, 
    :headers => {:content_type => 'image/jpeg'} 
) 

UPDATE(解决)

我需要使用RESTClient实现,因为我需要通过将它传递到另一个服务器(因此在PUT 'URL')。

我的问题是在图像解码我不剥出

data:image/jpeg;base64, 

然后用这个代码:

raw_response = RestClient.put(url, 
           file_binary, 
           {:content_type => imageContentType}) 

我能得到它把图像和设置正确的内容类型。下面的答案确实有帮助,因为我试图确保图像正确解码,而不是。

回答

0

这很简单。首先,你需要解码base64编码文件。您将获得二进制文件表示。接下来使用ActionControllersend_data发送二进制数据。另外我还设置了一个文件名,以便将其传送给用户。

require 'base64' 

class SomeController < ApplicationController 
    def some_action 
    file_name   = permitted_params[:file_name] 
    file_base64_contents = permitted_params[:file_contents] 
    file_binary_contents = Base64.decode64(file_base64_contents) 

    # https://apidock.com/rails/ActionController/Streaming/send_data 
    send_data file_binary_contents, filename: file_name 
    end 
end 

我建议你用错误处理更新这个实现,以提高你的应用程序的安全性。还有一件事,不要使用RestClient。你为什么需要这里? Rails为您提供来自控制器的HTTP通信所需的所有东西。

如果您对此有任何疑问,请询问。祝你好运。