Ruby Post请求:PDF文件

时间:2014-06-02 23:11:14

标签: ruby api pdf post request

上传文档的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,而另一个路由使其在浏览器中查看。我遇到了问题(试图弄清楚它是Prawn 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."]}

我最初想的可能"文件"不应该直接包含在关键文件下的正文中,但当我评论出我的参数时,#34;文件"然后我收到了这个错误。

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

所以它似乎正在阅读文档密钥并希望获得文档值但不是。如果我将file.read更改为file,我会收到相同的错误

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

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

1 个答案:

答案 0 :(得分:5)

也许您需要将其作为多部分请求发送。由于您已经在使用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