如何保存一个Base64字符串作为一个图像使用红宝石

如何保存一个Base64字符串作为一个图像使用红宝石

问题描述:

我在我的集​​成的Ruby on Rails应用程序与USPS航运体系。一旦你犯了一个邮资的请求,你付出代价的邮费和它的不可退还。

I'm integrating my Ruby on Rails app with a usps shipping system. Once you make a postage request, you pay for that postage and it's nonrefundable.

邮资的请求将返回,包括一个base64字符串,它是运输标签的XML响应。

Postage requests will return you an xml response including a base64 string, which is the shipping label.

我能够呈现在视图中运输标签,但使它万无一失,我希望能够保存的base64字符串作为形象我的服务器上的事件有事之间的运输标签代(​​为它付出)和邮寄所以它可能不买一个新的重印。

I'm able to render the shipping label in a view, however to make it foolproof, I would like to be able to save that base64 string as an image on my server in the event that something happens to the shipping label between generation (paying for it) and mailing so it may be reprinted without buying a new one.

我的第一个想法是如下:

My first thoughts were as follows

# Attempt 1
File.open('shipping_label.gif', 'w+') {|f|
    f.puts Base64.decode64(base_64_encoded_data)
}

# Attempt 2
File.open('shipping_label.gif', 'w+') {|f|
    f.puts Base64.decode64(Base64.decode64(base_64_encoded_data))
}

无论是工作。

在写入二进制数据到一个文件,比如是一个图像的情况下,使用IO#把危害和最好避免。应该以二进制模式,这是LF-仅平台如UNIX或OS X的大部分无关的,但是在CRLF的如视窗势在必行被写入。 IO#提出还追加换行符在这是无效的文件的末尾。

When writing binary data to a file, such as is the case with an image, using IO#puts is hazardous and best avoided. You should be writing in binary mode, which is mostly irrelevant on LF-only platforms such as UNIX or OS X, but is imperative on CRLF ones such as Windows. IO#puts also appends a newline at the end of the file which is invalid.

最好的方法是指定在公开征集正确的标志:

The best approach is to specify the correct flag on the open call:

File.open('shipping_label.gif', 'wb') do|f|
  f.write(Base64.decode64(base_64_encoded_data))
end

例如,看到IO#打开文档页面的意见:

For example, see the comment on the IO#open documentation page:

http://apidock.com/ruby/IO/open/class