1

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

Community
  • 1
  • 1
Mio
  • 1,412
  • 2
  • 19
  • 41
  • Why does that concern you? You can do manual serialization/de-serialization of your files, but why bother if browser and Rails will do that for you with `multipart/form-data`. – EugZol Aug 28 '15 at 13:47
  • Because for the moment all my api is a json api and I have to write blueprint documentation. For the moment I have to do thing like that. https://github.com/apiaryio/api-blueprint/issues/100#issuecomment-48290545 – Mio Aug 28 '15 at 13:57

1 Answers1

1

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.

EugZol
  • 6,476
  • 22
  • 41