ruby-on-rails - Convert pdf file to base64 string
问题描述
I have working Paperclip gem in my app for documents (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
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?
解决方案
你需要先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"
推荐阅读
- javascript - 无法绑定到“pdfTitle”,因为它不是“app-pdf-viewer”的已知属性
- node.js - TypeORM:如何在 typeORM 中应用泛化/专业化?
- sql - 如何为这个问题编写 sql SELECT 查询?
- javascript - Angular 10 - 从 ByteArray 数据下载文件
- excel - 如何在图表上显示矢量线及其对应值
- ios - 钥匙串无法正确导入 p12,系统钥匙串看起来很乱
- c++ - “setrlimit()”不影响正在运行的进程
- amazon-web-services - AWS Cloudwatch 指标上的数学表达式未提供预期输出
- bash - 文件处理:组合具有不同列数和行数的多个文件
- validation - 如何验证车牌字符/代码点?