2017-06-22 69 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通信所需的所有東西。

如果您對此有任何疑問,請詢問。祝你好運。