mardi 5 février 2019

How to consume Multipart/form-data via Ruby Controllers?

I know I'm receiving a file with Content-Type: multipart/form-data in my controller and I understand the file was uploaded with something like this:

body[:uploaded_data] = Faraday::UploadIO.new(path, mime_type, hash[:filename])

and the content of the file I receive is like this

    -------------RubyMultipartPost
Content-Disposition: form-data; name="filename"

1_BsKbDTA9ZUVroeJ7asId4Q.png
-------------RubyMultipartPost
Content-Disposition: form-data; name="uploaded_data"; filename="RackMultipart20190205-12268-1eli4dv"
Content-Length: 34441
Content-Type: image/png
Content-Transfer-Encoding: binary

‰PNG


 IHDR
awùé¨gP\ÆñÇèŒÎÌ_ý....

I'm trying to parse this so that I only get the content of the png file and save it as an actual png file.

I started by making a mock Rack env and parse it

env = Rack::MockRequest.env_for(
        '/',
        'CONTENT_TYPE' => request.headers['Content-Type'],
        'CONTENT_LENGTH' => request.body.length,
        'rack.input' => StringIO.new(request.body.read),
    )
    parsed_message = Rack::Multipart.parse_multipart(env)

and I know parsed_message['uploaded_data'] has the second part but I still don't know how to properly parse out the 4 lines that include Content-Disposition, Content-Length, Content-Type, Content-Transfer-Encoding and get only the file content.

Any ideas are appreciated!

Aucun commentaire:

Enregistrer un commentaire