php – It is possible to upload binary files to the server through a REST web service. How?


I am currently working on the development of a web system with Laravel 5.

Right now I need to upload binary files (pdf, images, etc) but without using web forms.

My query is: is it possible to do this with a REST web service?

I understand that it can be done by encoding the binary file in base64 but I don't know if this is the most correct way or if there is a more efficient way to do it.


You could use FormData which allows you to submit information as if it were a form, but without the form. You have to know a few things (such as the destination URL, the method used, and the required parameters), but from there it's (almost) like any other AJAX call:

  • Create a variable of the FormData class
  • Add the file selected by the user
  • Make the request with AJAX

The code would look like this (variation of this answer to a similar question on StackOverflow):

var misDatos = new FormData();
misDatos.append('fichero', subirfichero.files[0]);

  url: 'carga.php',
  type: 'POST',
  processData: false, // importante o recibirás un fallo de seguridad
  contentType: false, // importante o recibirás un fallo de seguridad
  dataType : 'json',
  data: misDatos

As you mention, you could also encode the file in base 64 and send it that way. That would work, but the encrypted files will be up to 40% larger than the original size , which may not be very convenient if the file is very large.

Scroll to Top