Ruby on rails 使用加铺(rails gem)使用convertapi转换文件
我正在开发一个Rails应用程序,将存储在AmazonS3上的Word文件发送到,以便转换为PDF。我使用来管理文件,使用来发出实际请求Ruby on rails 使用加铺(rails gem)使用convertapi转换文件,ruby-on-rails,curb,convertapi,Ruby On Rails,Curb,Convertapi,我正在开发一个Rails应用程序,将存储在AmazonS3上的Word文件发送到,以便转换为PDF。我使用来管理文件,使用来发出实际请求 # model with property has_attached_file :attachment def convert_docx_to_pdf base = "https://do.convertapi.com/Word2Pdf" api_key = '*****' file = open(attachment.url)
# model with property has_attached_file :attachment
def convert_docx_to_pdf
base = "https://do.convertapi.com/Word2Pdf"
api_key = '*****'
file = open(attachment.url)
c = Curl::Easy.new(base)
c.multipart_form_post = true
c.http_post(
Curl::PostField.file('thing[file]', file.path),
Curl::PostField.content('ApiKey', api_key)
)
end
我正试图按照文件的路缘
当我从rails控制台运行它时,它只返回true
。我想捕获生成的PDF
(如果我在convertapi上手动上传文件,我已经验证了这一点。)
更新日期09.18.15
我实施了乔纳斯建议的改变。以下是新代码:
def convert_docx_to_pdf
base = "https://do.convertapi.com/Word2Pdf"
api_key = ENV['CONVERTAPI_API_KEY']
file = open(attachment.url)
Curl::Easy.new('https://do.convertapi.com/Word2Pdf') do |curl|
curl.multipart_form_post = true
curl.http_post(Curl::PostField.content('ApiKey', api_key), Curl::PostField.file('File', file.path))
return curl.body_str
end
end
仍然没有运气,curl.body\u str
只返回“坏请求”
(
file.path=/var/folders/33/nzmm899s4jg21mzljmf9557c0000gn/T/open-uri20150918-13136-11z00lk
)这是在多部分post请求中使用路缘的正确方法:
Curl::Easy.new('https://do.convertapi.com/Word2Pdf') do |curl|
curl.multipart_form_post = true
curl.http_post(Curl::PostField.content('ApiKey', 'xxxxxxxxx'), Curl::PostField.file('File', 'test.docx'))
File.write('out.pdf', curl.body_str)
end
祝你有愉快的一天原来问题很简单。convertapi的Word-to-PDF转换工具需要具有Word扩展名的文件。在将文件发送到S3的过程中,我丢失了扩展名。(
file.path=/var/folders/33/nzmm899s4jg21mzljmf9557c0000gn/T/open-uri20150918-13136-11z00lk
)我能够通过针对convertapi web gui测试从S3提取的一个实际文件来验证这一点
理想情况下,我会确保在提交到S3时不会丢失扩展,但同时以下代码会起到作用:
def convert_docx_to_pdf
base = "https://do.convertapi.com/Word2Pdf"
api_key = ENV['CONVERTAPI_API_KEY']
file = open(attachment.url)
local_file_path = "#{file.path}.docx"
FileUtils.cp(file.path, local_file_path) # explicitly set the extension portion of the string
Curl::Easy.new('https://do.convertapi.com/Word2Pdf') do |curl|
curl.multipart_form_post = true
binding.pry
curl.http_post(Curl::PostField.content('ApiKey', api_key), Curl::PostField.file('File', local_file_path))
# Write to PDF opened in Binary (I got better resulting PDFs this way)
f = File.open('public/foo.pdf', 'wb')
f.write(curl.body_str)
f.close
end
FileUtils.rm(local_file_path)
end
非常感谢您的帮助,我已经实现了您建议的更改,运气不好(请参阅更新帖子)。为什么要使用file=open(attachment.url)和后者file.path?如果您使用Curl::PostField.file('file',attachment.url')@Jonas,这也不起作用,但也许可以理解,因为
attachment.url
只是一个字符串。API需要一个file对象,这就是file=open(attachment.url)
的作用。