gpt4 book ai didi

ruby-on-rails - 在 Ruby 中打开文件返回空文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:19 25 4
gpt4 key购买 nike

我目前正在尝试将 pdf 存储在散列中以用于 ruby​​ 中的 api 调用。 pdf 的路径存储为:

/Users/myUserName/Desktop/REPOSITORY/path_to_file.pdf

我正在使用一个 block 将文件存储在散列中:

File.open(pdf_location, "rb") do |file|
params = {
other irrelevant entries
:document => file
}
pdf_upload_request('post', params, headers)
end

我从服务器收到一个 400 错误,说我的文档是空的,当我执行 puts file.read 时,它是空的。但是,当我访问文件路径时,很明显该文件不是空的。我在这里错过了什么吗?任何帮助将不胜感激。谢谢!

编辑------

我用录像机记录了我的http请求,这里是:

request:
method: post
uri: request_uri
body:
encoding: US-ASCII
string: ''
headers:
Authorization:
- Bearer 3ZOCPnwfoN7VfdGh7k4lrBuEYs4gN1
Content-Type:
- multipart/form-data; boundary=-----------RubyMultipartPost
Content-Length:
- '246659'

所以我认为问题不在于我使用多部分编码发送文件

更新--------

pdf 的文件路径是从 url 生成的,并存储在我的应用程序的 tmp 文件夹中。它们是通过这种方法生成的:

def get_temporary_pdf(chrono_detail, recording, host)
auth_token = User.find(chrono_detail.user_id).authentication_token
# pdf_location = "https://54.84.224.252/recording/5/analysis.pdf/?token=Ybp37kw7HrSt8NyyPnBZ"
pdf_location = host + '/recordings/' + recording.id.to_s + '/analysis.pdf/?format=pdf&download=true&token=' + auth_token
filename = "Will" + '_' + recording.id.to_s + '_' + Date.new.to_s + '.pdf'
Thread.new do
File.open(Rails.root.join("tmp",filename), "wb") do |file|
file.write(open(pdf_location, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE}).read)
end
end
Rails.root.join("tmp",filename)
end

然后使用 api 调用调用它们:

client.upload_document(patient_id, file_path, description)

我可以在我的临时文件夹中实际看到它们,并且可以通过预览查看它们。一切似乎都有效。但作为不确定性的测试,我更改了 file_path 以指向不同的 pdf:

Users/myUsername/Desktop/example.pdf.

使用此文件路径有效。 pdf 已正确上传到第三方系统,我可以在那里实际看到它。您认为这是否意味着 tmp 文件夹或我如何生成临时 pdf 有问题?

最佳答案

最有可能的是,API 期待一个带有 Content-Type: multipart/form-data 的 POST。仅发送文件句柄(document: file 所做的)是行不通的,因为文件句柄只与您的本地 Ruby 进程相关;甚至将二进制字符串作为参数发送也行不通,因为您的内容类型未正确设置为对文件进行编码。

由于您已经在使用 HTTParty,因此您可以使用 HTTMultiParty 来解决这个问题:

require 'httmultiparty'
class SomeClient
include HTTMultiParty
base_uri 'http://localhost:3000'
end

SomeClient.post('/', :query => {
:foo => 'bar',
:somefile => File.new('README.md')
})

关于ruby-on-rails - 在 Ruby 中打开文件返回空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com