Learn how to upload a file within a form asynchronously with jQuery ajax.

Send a file with the traditional way is kind of easy task (form ,file input and submit button). However it's not so easy when we want to do it with javascript and it's not so intuitive. To accomplish this task we need jQuery (or use the xmlHttpRequest function) and patience. 

The html form needs to look like this, a simple file input (the text parameters is optional, is only to prove that we can send more information, not only the file).

<form id="myform" method="post">
  <input type="text" name="username" />
  <input type="file" name="upload" />

To send a file with ajax you need to send an ajax request sending POST data, the following code will do the trick for you :

Note: in this example we are expecting from the server json (dataType:json) , you can send your own response type.

var form = document.getElementById("myform");
// or with jQuery
//var form = $("#myform")[0];

  data: new FormData(form),// the formData function is available in almost all new browsers.
  dataType:"json", // Change this according to your response from the server.
   console.log("Request finished.");


The variable form will be the node element of the form. Then we just need to retrieve the file in the backend.

Symfony 2

We will retrieve the file with the request object of the controller. Then we'll move it and return a JSON Response.

// Important to use these statemenets, the json response is optional for our response.
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

public function retrieveAction(Request $request){
   // retrieve the file with the name given in the form.
   // do var_dump($request->files->all()); if you need to know if the file is being uploaded.
   $file = $request->files->get('upload');
   $status = array('status' => "success","fileUploaded" => false);
   // If a file was uploaded
      // generate a random name for the file but keep the extension
      $filename = uniqid().".".$file->getClientOriginalExtension();
      $path = "/path/where/we/want-to-save-the-file";
      $file->move($path,$filename); // move the file to a path
      $status = array('status' => "success","fileUploaded" => true);

   return new JsonResponse($status);

Plain PHP

$info = pathinfo($_FILES['upload']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "thenamethat you want.".$ext; 

$target = 'path-where-to-save-the-file/'.$newname;
move_uploaded_file( $_FILES['upload']['tmp_name'], $target);

You can set up the backend according to your needs (if you're not using php for example), have fun !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.