如何在 Ruby 中给定 URL 以 base64 编码媒体 [英] How to encode media in base64 given URL in Ruby
本文介绍了如何在 Ruby 中给定 URL 以 base64 编码媒体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将图像上传到 PingFM.他们的文档说:
I'm trying to upload an image to PingFM. Their documentation says:
media – base64 encoded media data.
我可以通过 URL 访问此图像.我试过(几乎猜到了)这个:
I can access this image via the URL. I tried (practically guessed) this:
ActiveSupport::Base64.encode64(open("http://image.com/img.jpg"))
但我收到此错误:
TypeError: can't convert Tempfile into String
from /usr/lib/ruby/1.8/base64.rb:97:in `pack'
from /usr/lib/ruby/1.8/base64.rb:97:in `encode64'
from (irb):19
from :0
推荐答案
open
方法:
open("http://image.com/img.jpg")
正在返回一个 Tempfile 对象,而 encode64
需要一个字符串.
is returning a Tempfile object, while encode64
expects a String.
在临时文件上调用 read
应该可以解决问题:
Calling read
on the tempfile should do the trick:
ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
这篇关于如何在 Ruby 中给定 URL 以 base64 编码媒体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文