【问题标题】:How to send PNG image using Net::HTTP如何使用 Net::HTTP 发送 PNG 图像
【发布时间】:2016-08-04 18:31:35
【问题描述】:

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

如何编码?

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

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

【问题讨论】:

  • 这取决于第三方 API 是否需要您的文件。请参阅 API 文档。 Minimal, Complete, and Verifiable example
  • 启动 Wireshark。比较来自 Postman 的 POST 请求和来自 Net::HTTP 的 POST 请求。 This answer 可以帮到你。
  • @Uzbekjon 我的问题是,邮递员是如何编码的?这是一个 rinky dink API,其创建者不知道问题的答案。但它适用于 Postman,因此是我的问题。
  • 您指的是哪个邮递员宝石?我刚刚浏览了这个postman's code,尽管自述文件说它会调用 webhook,但它不是。
  • @Uzbekjon 我实际上是在谈论 Postman 应用程序,而不是 ruby​​ gem。它使您可以轻松地构建请求。感谢您的调查。

标签: ruby-on-rails ruby encoding paperclip


【解决方案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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 2018-05-25
  • 2013-02-04
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多