将pdf文件转换为base64字符串

Convert pdf file to base64 string

我在我的文档(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 错误有什么建议吗?

您需要先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"

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

不过我设法找到了回形针方法:

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