2017-05-05 42 views
0

我正在使用ruby本机库来执行multipart/form-data API POST调用。 在这个调用中,我发送了json和文件,但是从服务器端文件没有正确上传。有时候,它会成功上传。通过Net :: Http在ruby上传PDF文件到外部源

boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW' 
url = URI("http://localhost:3000/pdfs") 

http = Net::HTTP.new(url.host, url.port) 
http.use_ssl = true 
http.verify_mode = OpenSSL::SSL::VERIFY_NONE 
request = Net::HTTP::Post.new(url) 

request["authorization"] = "Bearer ddghfgdjh54544fdgdfghj" 
request["accept"] = 'application/json' 
request["content-type"] = "multipart/form-data; boundary=#{boundary}" 
request["cache-control"] = 'no-cache' 



body = [] 
# JSON data 
body << "--#{boundary}\r\nContent-Disposition: form-data;" 
body << "name=\"profile\"\r\n\r\n" 
body << {user: {name:"xyz",email:"[email protected]"} }.to_json 
body << "\r\n" 

#File data 

    body << "--#{boundary}\r\n" 
    body << "Content-Disposition: form-data;" 
    body << "name=\"profile\"; filename=\"#{username}.pdf\"\r\nContent-Type: application/pdf\r\n" 
    body << "#{File.read('/home/pdfs/profile.pdf')}\r\n" 


request.body = body.join 
response = http.request(request) 
+0

怎么做JSON API POST调用和文件作为多/ form-data的 – santoshkumar

回答

0

我想你应该使用BASE64进行文件上传。 base64编码的主要用例是当您想要使用一组受限制的字符存储或传输数据时;即当你无法在每个字节中传递任意值时。 Base64允许将8位数据编码为6位,以用于在这些类型的格式上传输

将基本64编码的字符串解码为其原始表示。

ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==") 
# => "Original unencoded string" 
+0

,我将请求发送到第三方API – santoshkumar

+0

为此,您需要提及你的代码在这个问题上 – Sunny