【问题标题】:Ruby Post Request: PDF FileRuby 发布请求:PDF 文件
【发布时间】:2014-06-02 23:11:14
【问题描述】:

上传文档的API例子是这样的

headers = {
    'Authorization': 'Bearer ACCESS_TOKEN',
}
params = {
    'doctor': 'https://drchrono.com/api/doctors/1234',
    'patient': 'https://drchrono.com/api/patients/5678',
    'description': 'Short document description here',
    'date': '2014-02-24',
    'metatags': json.dumps(['tag1', 'tag2']),
}
with open('/path/to/your.pdf', 'rb') as f:
    files = {'document': f}
    requests.post(
        'https://drchrono.com/api/documents',
        data=params, files=files, headers=headers,
    )

我使用 Prawn 创建 PDF。一条路线自动下载 PDF,而另一条路线将其呈现以在浏览器中查看。我遇到了问题,所以(试图弄清楚是虾 PDF 问题还是 PDF 问题)我从网上下载了一个相当基本的 PDF。同样的问题。我正在使用 HTTParty 发送我的 POST 请求。

  headers = {'Authorization' => 'Bearer ' + access_token}
  File.open("#{Rails.root}/app/assets/test.pdf", "rb") do |file|
    params = {
      'document' => file.read,
      'doctor' => 'https://drchrono.com/api/doctors/' + doctor.id,
      'patient' => 'https://drchrono.com/api/patients/' + patient.id,
      'description' => 'Report',
      'date' => date
    }
    response = HTTParty.post('https://drchrono.com/api/documents', :headers => headers, :body => params)
    puts response
    data = JSON.parse(response.body)
    puts data
 end

我收到以下错误。

{"document"=>["No file was submitted. Check the encoding type on the form."]}

我最初认为也许“文档”不应该直接包含在关键文档下的正文中,但是当我注释掉我的参数“文档”时,我收到了这个错误。

{"document"=>["This field is required."]}

因此,它似乎正在读取文档密钥并期望获得文档值,但事实并非如此。如果我将 file.read 更改为 file 我会收到同样的错误

{"document"=>["No file was submitted. Check the encoding type on the form."]}

我觉得答案可能非常简单,但我已经被困了一段时间了。有什么想法吗?

【问题讨论】:

标签: ruby api pdf post request


【解决方案1】:

也许您需要将其作为多部分请求发送。由于您已经在使用 HTTParty,您可能会发现 httmultiparty Gem 很有用。示例:

require 'httmultiparty'

class DrChronoClient
  include HTTMultiParty
  base_uri 'https://drchrono.com/api'
end

File.open("#{Rails.root}/app/assets/test.pdf", "rb") do |file|
  headers = {
    :Authorization => 'Bearer ' + access_token
  }

  params = {
    :document => file.read,
    :doctor => 'https://drchrono.com/api/doctors/' + doctor.id,
    :patient => 'https://drchrono.com/api/patients/' + patient.id,
    :description => 'Report',
    :date => date
  }

  response = DrChronoClient.post('documents', :query => params, :headers => headers)
  puts response
  data = JSON.parse(response.body)
  puts data
end

【讨论】:

  • 非常感谢。这些正是我觉得最令人沮丧的问题类型;那些有一些关于这些东西如何工作的基本信息的地方,我不知何故完全错过了,并且无缘无故地花了几个小时在虚假的前提下修补。
  • 不客气!毕竟,CS 学位不会为您购买这些知识。与许多事情一样,这只是经验问题。万事如意!
  • 我们现在有了管理 drchrono Google 群组的版主和开发人员,请随时在此处发布问题 - groups.google.com/forum/#!forum/drchrono-api
猜你喜欢
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
相关资源
最近更新 更多