vendredi 16 décembre 2016

Sinatra ajax file uploading: invalid byte sequence in UTF-8

The title might sound trivial, but it's not that easy.

I have a Rails 3 app has an API powered by Sinatra. What I'm trying to do is to upload a picture from my Insomnia REST client.

And here's the problem.

First, I send my picture as a file parameter.

Insomnia REST client interface

My entry point is this method:

app.post '/account/avatar', authorization: true do
  query('account/avatar').upload(params[:file])
end

But params[:file] content seems a bit weird.

0> params[:file]
=> "\xFF\xD8\xFF\xE0\u0000\u0010JFIF\u0000\u0001\u0001... (you got the point)

Most String methods fail with the following error:

0> params[:file].present?
=> invalid byte sequence in UTF-8

But I was expecting to see something like this:

params[:file] = {
  :filename=>"mock-up-1.jpg",
  :type=>"image/jpeg",
  :name=>"file",
  :tempfile=>#<Tempfile:/var/folders/dq/nylzy6q151nc7n4y5bj4b6y9pyqtgz/T/RackMultipart20140929-13931-1qucfg1>,
  :head=>"Content-Disposition: form-data; name=\"file\"; filename=\"foo.jpg\"\r\nContent-Type: image/jpeg\r\n"
}

My headers are:

Content-Type: multipart/form-data
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
X-File-Name: mock-up-1.jpg

Aucun commentaire:

Enregistrer un commentaire