4

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

Sohail Aslam
  • 727
  • 4
  • 24
  • Look at some possible solutions here: https://stackoverflow.com/questions/4083702/posting-a-file-and-associated-data-to-a-restful-webservice-preferably-as-json – Alok Swain Mar 19 '20 at 14:00

1 Answers1

5

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.

Paweł Gościcki
  • 9,066
  • 5
  • 70
  • 81
max
  • 96,212
  • 14
  • 104
  • 165
  • I wanted to create a tempfile which will store the contents of the excel file given that i will only input file path thru JSON. is that possible? – Ross Agulto Mar 20 '20 at 05:17
  • 1
    @RossAgulto A path to what? If it's a file stored on the server there is no need to treat it like its as an upload in the first place. If it's a file on the the client I don't get how you think it's magically going to teleport itself to the server. – max Mar 20 '20 at 05:25
  • 1
    You can't just send a file path and expect the file contents to magically appear on the other end. If you want to send a file in JSON you need to base64 encode it as JSON has no binary support and send it as part of the json object. – max Mar 20 '20 at 05:36