[英]Convert pdf file to base64 string
I have working Paperclip gem in my app for documents (pdf, doc). 我在我的应用程序中使用Paperclip gem来处理文档(pdf,doc)。 I need to pass the document to some other third party application via post request.
我需要通过邮寄请求将文档传递给其他第三方应用程序。
I tried to convert the paperclip attachment via Base64 but it throws error: no implicit conversion of Tempfile into String 我尝试通过Base64转换回形针附件,但它会抛出错误:没有将Tempfile隐式转换为String
Here is how I did it: 我是这样做的:
# 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)
Do you have any suggestion how to avoid the Tempfile error? 你有什么建议如何避免Tempfile错误?
You need to read
file first. 您需要先
read
文件。
base_64_file = Base64.encode64(file_data.read)
Here is working example: 这是工作示例:
$ 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"
The answer from @3елёный didn't work to me - maybe because it's the S3 file. @3елёный的回答对我不起作用 - 也许是因为它是S3文件。
However I managed to find a way with Paperclip method: 但是我设法用Paperclip方法找到了一种方法:
file_data = Paperclip.io_adapters.for(url).read
base_64_file = Base64.encode64(file_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.