【问题标题】:In Ruby on Rails, how to set Base64 encoded string as a pdf attachment?在 Ruby on Rails 中,如何将 Base64 编码的字符串设置为 pdf 附件?
【发布时间】:2016-05-26 03:23:49
【问题描述】:

我有一个 Base64 编码的 PDF 数据,并希望使用 ActionMailer 将其设置为邮件的附件。

我尝试过如下方式(假设 Base64 编码的 pdf 数据在 base64_encoded_string 中):

attachments['attachment.pdf'] = {
  mime_type: 'application/pdf',
  encoding: 'base64',
  content: base64_encoded_string
}

但是当我在收到的电子邮件中打开附加的 pdf 文件时,文件已损坏。

现在我提前解码一个Base64字符串让ActionMailer编码Base64,它工作没有任何问题。

attachments[File.basename('attachment.pdf')] = Base64.decode64(base64_encoded_string)

如何直接将Base64编码的字符串设置为pdf附件?

【问题讨论】:

  • 与 gif 相同的问题,你有没有机会找到这个问题的答案? (我的意思是即使是 Base64 编码的内容,它也会在电子邮件中被破坏)

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

似乎我找到了解决方案。如果您提供 base64 字符串作为内容,请确保指定编码。否则 Rails 将对已经编码的字符串进行第二次编码。

attachments['base64_file.pdf'] = {
  mime_type: 'application/pdf',
  encoding: 'base64',
  content: base64_string
}

【讨论】:

    【解决方案2】:

    来自 Rails document

    Mail 会自动对附件进行 Base64 编码。如果你想 不同的东西,对您的内容进行编码并传入编码的内容 Hash 中的内容和编码到附件方法。

    因此,您只需将内容设置为 base64 字符串,而无需指定编码。它会起作用的,这就是我在我的项目中所做的:

    attachments['attachment.pdf'] = {
      mime_type: 'application/pdf',
      content: base64_encoded_string
    }
    

    【讨论】:

    • 谢谢,我按照你写的方法试过了,但还是无法打开附件中的 pdf 文件。也许我必须通过检查二进制本身来调查问题。
    【解决方案3】:

    这个链接应该有帮助。

    http://apidock.com/rails/ActionMailer/Base/attachments

    attachments['attachment.pdf'] = { mime_type: 'application/pdf', 
                                      content:  File.read('/path/to/filename.pdf')}
    

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 2012-11-12
      • 2011-08-08
      • 1970-01-01
      • 2017-03-24
      • 2010-09-19
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多