Zack Xu Zack Xu - 28 days ago 20
Ruby Question

How to convert base64 encoded string to HTTP::FormData::File in Ruby?

I have a base64 encoded string of a pdf file, which I can decode using Ruby

Base64.decode(the_string)


Now I want to convert it to an object of type
HTTP::FormData::File
which I can then upload using http post to AWS S3.

How do I do this WITHOUT writing out the file to disk and reading it back in using

HTTP::FormData::File.new("/path/to/file.pdf")


Thank you

Answer

I'm guessing you're using the http-form_data gem. In that case, your answer is in the very first example in the HTTP::FormData::File docs. For posterity:

Usage with StringIO

io = StringIO.new "foo bar baz"
FormData::File.new io, :filename => "foobar.txt"

And so:

require "stringio"
require "base64"

io = StringIO.new(Base64.decode64(the_string))
file = HTTP::FormData::File.new(io, filename: "some_filename.txt")