简体   繁体   English

将回形针pdf从S3转换为base64(Rails)

[英]Convert paperclip pdf from S3 to base64 (Rails)

I'm sending a base64 of a PDF to an external API endpoint in a Rails app. 我正在将PDF的base64发送到Rails应用程序中的外部API端点。

This occurs regularly with different PDFs for different users. 对于不同的用户,使用不同的PDF通常会发生这种情况。 I'm currently using the Paperclip gem. 我目前正在使用回形针gem。

The problem is getting the PDF into a format that I can then convert to base64. 问题是将PDF转换成可以转换为base64的格式。

Below works if I start with a PDF locally and .read it, but not when it comes from S3. 如果我从本地开始使用PDF并进行.read则以下方法.read ,但是当它来自S3时则无效。

Code: 码:

def self.get_pdf(upload_id)

  # get URL for file in S3 (for directly accessing the PDF in browser)
  # `.generic` implemented via `has_attached_file :generic` in model
  # `.expiring_url` is paperclip syntax for generating a URL
  s3_url = Upload
      .find(upload_id)
      .generic
      .expiring_url(100)

  # open file from URL
  file = open(s3_url)

  # read file
  pdf = File.read(file)

  # convert to base64
  base64 = Base64.encode64(File.open(pdf, "rb").read)
end

Error: 错误:

OpenURI::HTTPError (404 Not Found): OpenURI :: HTTPError(找不到404):

Ideally this can just occur in memory instead of actually download the file. 理想情况下,这可能只是在内存中发生,而不是实际下载文件。

Streaming-in a base64 from S3 while streaming out the API request would be awesome but I don't think thats an option here. 从S3流进base64的同时,流出API请求会很棒,但是我认为这不是一个选择。

UPDATE: 更新:

  • signed URLs from Cyberduck + Michael's answer will work 来自Cyber​​duck和Michael的答案的签名URL会起作用
  • paperclip URLs fail + Michael's answer results in below error 回形针URL失败+ Michael的回答导致以下错误

Error: 错误:

The specified key does not exist. 指定的密钥不存在。

Unfortunately I need to use Paperclip so I can generate links and download PDFs on the fly, based on the uploads table records in my db. 不幸的是,我需要使用Paperclip,以便可以基于数据库中的uploads表记录生成链接并即时下载PDF。

Is there is a technicality about paperclip links I don't understand? 我不了解回形针链接是否具有技术性?

base64 =  Base64.encode64( get_me(s3_url).body ).gsub("\n", '')

def get_me(url)
    uri = URI(url)
    req = Net::HTTP::Get.new(uri)
    req['Any_header_you_might_need'] = 'idem'
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(req)
    end
    return res
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM