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.
Postage requests will return you an xml response including a base64 string, which is the shipping label.
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)) }
Neither work.
When writing binary data to a file, such as is the case with an image, you cannot use text printing tools like IO#puts
.
There's two things you need to ensure:
write
instead of puts
as write
can work on arbitrary data, but puts
(literally "put string") is exclusively for text.Combining these you get:
File.open('shipping_label.gif', 'wb') do |f| f.write(Base64.decode64(base_64_encoded_data)) end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With