Reputation: 41
Is there a way to convert a string into ActionDispatch::Http::UploadedFile
I need it to be able to pass the file path in an API request to process the inserting of excel to a database as I want to do file upload using rest API rather than the browser.
Thank you
Upvotes: 4
Views: 2744
Reputation: 101811
Just create a Tempfile instance and use it to initialize a ActionDispatch::Http::UploadedFile
:
tempfile = Tempfile.new(file_name)
tempfile.binmode
# assumes you have a Base64 encoded string passed through JSON
tempfile.write(Base64.decode64(string))
tempfile.rewind
# for security reasons it is necessary to have real content type
content_type = `file --mime -b #{tempfile.path}`.split(';')[0]
ActionDispatch::Http::UploadedFile.new(
tempfile: tempfile,
type: content_Type,
filename: 'original_file_name.xls'
)
It's not that well documented but the source code is really simple as ActionDispatch::Http::UploadedFile basically just wraps the tempfile with some metadata. All the hard work of actually pulling files out of the multipart request is done by Rack. See Sending files to a Rails JSON API for a complete controller example.
Upvotes: 5