【问题标题】:Convert pdf file to base64 string将pdf文件转换为base64字符串
【发布时间】:2018-06-17 00:21:03
【问题描述】:

我的应用程序中有用于文档(pdf、doc)的 Paperclip gem。我需要通过 post 请求将文档传递给其他第三方应用程序。

我尝试通过 Base64 转换回形针附件,但它抛出错误: 没有将 Tempfile 隐式转换为 String

我是这样做的:

# get url from the paperclip file
url = document.doc.url # https://s3-ap-southeast-1.amazonaws.com/xx-eng/documents/xx/000/000/xx/original/doc.pdf

file_data = open(url)

# Encode the bytes to base64 - this line throw error
base_64_file = Base64.encode64(file_data)

您对如何避免 Tempfile 错误有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails ruby paperclip


    【解决方案1】:

    您需要先read 归档。

    base_64_file = Base64.encode64(file_data.read)
    

    这是工作示例:

    $ bundle exec rails c
    => file = open("tmp/file.pdf")
    #> #<File:tmp/receipts.pdf>
    => base_64 = Base64.encode64(file)
    #> TypeError: no implicit conversion of File into String
    => base_64 = Base64.encode64(file.read)
    #> "JVBERi0xLjQKMSAwIG9iago8PAovVGl0b/BBQEPgQ ......J0ZgozMDM0OQolJUVPRgo=\n"
    

    【讨论】:

      【解决方案2】:

      @3елёный 的回答对我不起作用——可能是因为它是 S3 文件。

      但是我设法用回形针方法找到了一种方法:

      file_data = Paperclip.io_adapters.for(url).read
      base_64_file = Base64.encode64(file_data)
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 2021-12-12
        • 1970-01-01
        • 2017-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        相关资源
        最近更新 更多