我会在网络服务器中下载 PDF 文件。我使用 Net::HTTP Ruby 类。
def open_file(url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.path)
request.basic_auth(self.class.user, self.class.password)
http.request(request)
end
它有效,我检索了我的 PDF 文件,它是一个类似以下的字符串:%PDF-1.3\n%\ ...
我有一个返回结果的方法:
def file
result = open_file(self.file_url)
times = 0
if result.code == 404 && times <= 5
sleep(1)
times += 1
file
else
result.body
end
end
(这是一种递归方法,因为该文件可能在服务器上不再存在)
但是当我用回形针保存此文件时,出现错误:Paperclip::AdapterRegistry::NoHandlerError (No handler found for "%PDF-1.3\n% ...
我尝试使用 StringIO
操作该文件...没有成功:(。
有人有想法吗?
最佳答案
假设您获得的 PDF 对象没问题(我不是 100% 确定),那么您可以这样做:
file = StringIO.new(attachment) #mimic a real upload file
file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
file.original_filename = "your_report.pdf"
file.content_type = "application/pdf"
然后用回形针保存文件。
关于ruby - Net::HTTP 获取 PDF 文件并用回形针保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495844/