ruby - Net::HTTP 获取 PDF 文件并用回形针保存

标签 ruby ruby-on-rails-3 paperclip

我会在网络服务器中下载 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"

然后用回形针保存文件。

(来自“Save a Prawn PDF as a Paperclip attachment? ”)

关于ruby - Net::HTTP 获取 PDF 文件并用回形针保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495844/

相关文章:

ruby - 如何从 Unix 命令行与 MS Exchange 日历交互?

ruby-on-rails - rails - 如何以美国格式显示和保存日期?

mysql - 对 rails 的 mysql 查询的更正

ruby-on-rails - 带有回形针 Docx content_type 的 Rails 将作为应用程序/zip 回来

ruby-on-rails - 如何使用回形针检查一个文件是否等于目录中的另一个文件

ruby - 如何更改 Ruby 中 FFI 调用的 STDOUT?

ruby-on-rails - ruby rails : models that do not have a table

javascript - rails : How to execute function using a button without reload pages

mysql - SQL 查询通过关联模型选择用户的 friend

ruby-on-rails - 使用回形针时heroku在哪里存储上传的文件