Mio
Mio

Reputation: 1502

Serialize and embed uploaded files to JSON

I have an API done with rails. I'm looking to upload multiple files in the same POST request. I would like to know if the only to do it by using form-data like mention here?

curl -X PATCH -H "Content-Type: multipart/form-data" -F "post[name]=wef" -F "post[catchphrase]=rteh reth erth erth" -F "post[posts_ids][]=8940" -F "post[screenshot1]=Ca9.png" -F "post[banner]=C34.png" -F  "post[icon]=60eb.jpg" 'http://example.com:3000/api/v1/5282/posts/111605.json?api_key=2s4ctv21vudsgreeegrge'

Thanks

Upvotes: 1

Views: 479

Answers (1)

EugZol
EugZol

Reputation: 6545

You can use base64 encoding.

On your client side:

HTML

<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">

Javascript

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}

Source: readAsDataURL documentation

If you don't use Javascript, make serializer for your platform. Data-URL is just data:[<MIME-type>][;charset=<encoding>][;base64],<data> (source)

On your server side:

Most likely you won't need to do anything at all, because paperclip/carrierwave will deserialize that stuff for you.

Upvotes: 1

Related Questions