如何使用 Net::HTTP 发送 PNG 图像
How to send PNG image using Net::HTTP
我正在尝试将 Paperclip 上传的图像发送到 API。
如何编码?
现在我正在使用 attachment.queued_for_write[:original].read
获取该 PNG 的实际文件内容,并尝试将其发送到我的请求正文中。但是服务器没有。
当我通过 Postman post 请求时,它工作正常。邮递员如何对此进行编码?不幸的是,尝试从 Postman 生成 Ruby 代码不起作用,它只是在请求正文中将文件显示为 [Object object]
。
Postman docs say it is using standard form post. A 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)
我正在尝试将 Paperclip 上传的图像发送到 API。
如何编码?
现在我正在使用 attachment.queued_for_write[:original].read
获取该 PNG 的实际文件内容,并尝试将其发送到我的请求正文中。但是服务器没有。
当我通过 Postman post 请求时,它工作正常。邮递员如何对此进行编码?不幸的是,尝试从 Postman 生成 Ruby 代码不起作用,它只是在请求正文中将文件显示为 [Object object]
。
Postman docs say it is using standard form post. A 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)