Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将pdf文件转换为base64字符串_Ruby On Rails_Ruby_Paperclip - Fatal编程技术网

Ruby on rails 将pdf文件转换为base64字符串

Ruby on rails 将pdf文件转换为base64字符串,ruby-on-rails,ruby,paperclip,Ruby On Rails,Ruby,Paperclip,我在我的文档应用程序(pdf,doc)中有可工作的回形针宝石。我需要通过post请求将文档传递给其他第三方应用程序 我试图通过Base64转换回形针附件,但出现错误: 没有将Tempfile隐式转换为字符串 我是这样做的: # 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

我在我的文档应用程序(pdf,doc)中有可工作的回形针宝石。我需要通过post请求将文档传递给其他第三方应用程序

我试图通过Base64转换回形针附件,但出现错误: 没有将Tempfile隐式转换为字符串

我是这样做的:

# 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错误有什么建议吗?

您需要先阅读
文件

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"
$bundle exec rails c
=>文件=打开(“tmp/file.pdf”)
#> #
=>base_64=Base64.encode64(文件)
#>TypeError:没有将文件隐式转换为字符串
=>base_64=Base64.encode64(file.read)
#>“jvberi0xljqkmsawig9iago8paovggl0b/BBQEPgQ……jzgozmdm0oqoljuvprgo=\n”

来自@3ёёыы的答案对我不起作用-可能是因为它是S3文件

然而,我设法找到了一种使用回形针的方法:

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