如何使用Net :: HTTP发送PNG图像

问题描述 投票:0回答:1

我正在尝试将Paperclip上传的图像发送到API。

我该如何编码?

现在我正在使用attachment.queued_for_write[:original].read来获取该PNG的实际文件内容,并尝试在我的请求正文中发送它。但服务器没有它。

当我通过Postman发布请求时,它工作正常。 Postman如何对此进行编码?不幸的是,尝试从Postman生成Ruby代码不起作用,它只是在请求正文中将文件显示为[Object object]

ruby-on-rails ruby encoding paperclip
1个回答
1
投票

Postman docs say它使用标准形式的帖子。一个quick search导致了这个代码:

require "net/http"
require "uri"

# Token used to terminate the file in the post body. Make sure it is not
# present in the file you're uploading.
# You might want to use `SecureRandom` class to generate this random strings
BOUNDARY = "AaB03x"

uri = URI.parse("http://something.com/uploads")
file = "/path/to/your/testfile.txt"

post_body = []
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name='datafile'; filename='#{File.basename(file)}'\r\n"
post_body << "Content-Type: text/plain\r\n"
post_body << "\r\n"
post_body << File.read(file)
post_body << "\r\n--#{BOUNDARY}--\r\n"

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = post_body.join
request["Content-Type"] = "multipart/form-data, boundary=#{BOUNDARY}"

http.request(request)
© www.soinside.com 2019 - 2024. All rights reserved.