jQuery Ajax File Upload [Answered]

Query explained:

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?

    type: "POST",
    timeout: 50000,
    url: url,
    data: dataString,
    success: function (data) {
        return false;

If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.

I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.

jQuery Ajax file upload – Answer #1:

File upload is not possible through AJAX.
You can upload file, without refreshing page by using IFrame.
You can check further details here.


With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

Answer #2:

Iframes are no longer needed for uploading files through ajax. I’ve recently done it by myself. Check out this:


Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types. Added progressbar html and css code.

var Upload = function (file) {
    this.file = file;

Upload.prototype.getType = function() {
    return this.file.type;
Upload.prototype.getSize = function() {
    return this.file.size;
Upload.prototype.getName = function() {
    return this.file.name;
Upload.prototype.doUpload = function () {
    var that = this;
    var formData = new FormData();

    // add assoc key values, this will be posts values
    formData.append("file", this.file, this.getName());
    formData.append("upload_file", true);

        type: "POST",
        url: "script",
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', that.progressHandling, false);
            return myXhr;
        success: function (data) {
            // your callback here
        error: function (error) {
            // handle error
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000

Upload.prototype.progressHandling = function (event) {
    var percent = 0;
    var position = event.loaded || event.position;
    var total = event.total;
    var progress_bar_id = "#progress-wrp";
    if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
    // update progressbars classes so it fits your code
    $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
    $(progress_bar_id + " .status").text(percent + "%");

How to use the Upload class

//Change id to your id
$("#ingredient_file").on("change", function (e) {
    var file = $(this)[0].files[0];
    var upload = new Upload(file);

    // maby check size or type here with upload.getSize() and upload.getType()

    // execute upload

Progressbar html code

<div id="progress-wrp">
    <div class="progress-bar"></div>
    <div class="status">0%</div>

Progressbar css code

#progress-wrp {
  border: 1px solid #0099CC;
  padding: 1px;
  position: relative;
  height: 30px;
  border-radius: 3px;
  margin: 10px;
  text-align: left;
  background: #fff;
  box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);

#progress-wrp .progress-bar {
  height: 100%;
  border-radius: 3px;
  background-color: #f39ac7;
  width: 0;
  box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);

#progress-wrp .status {
  top: 3px;
  left: 50%;
  position: absolute;
  display: inline-block;
  color: #000000;

Answer #3:

Ajax post and upload file is possible. I’m using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);

       url : 'upload.php',
       type : 'POST',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {

As you can see, you must create a FormData object, empty or from (serialized? – $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no terminó la acción de subir el archivo.';
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningún archivo fue subido.';
          $message = 'Error: servidor no configurado para carga de archivos.';
          $message= 'Error: posible falla al grabar el archivo.';
          $message = 'Error: carga de archivo no completada.';
     default: $message = 'Error: carga de archivo no completada.';
      echo json_encode(array(
               'error' => true,
               'message' => $message

Answer #4:

Simple Upload Form

   //form Submit
      var formData = new FormData($(this)[0]);
       url: 'fileUpload',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       enctype: 'multipart/form-data',
       processData: false,
       success: function (response) {
   return false;
<!--Upload Form-->
      <td colspan="2">File Upload</td>
      <th>Select File </th>
      <td><input id="csv" name="csv" type="file" /></td>
      <td colspan="2">
        <input type="submit" value="submit"/> 

Answer #5:

I’m pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.

Upload HTML:

<!DOCTYPE html>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            return false;

    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    <div id="output"></div>

In case you are working with php here’s a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.


if ($_POST["label"]) {
    $label = $_POST["label"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
} else {
    echo "Invalid file";

jQuery Ajax File Upload- Answer #6:

Here’s how I got this working:


<input type="file" id="file">
<button id='process-file-button'>Process</button>


$('#process-file-button').on('click', function (e) {
    let files = new FormData(), // you can consider this as 'data bag'
        url = 'yourUrl';

    files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'

        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (response) {
        error: function (err) {


if (isset($_FILES) && !empty($_FILES)) {
    $file = $_FILES['fileName'];
    $name = $file['name'];
    $path = $file['tmp_name'];

    // process your file


Answer #7:

Using pure js it is easier

async function saveFile(inp) 
    let formData = new FormData();           
    formData.append("file", inp.files[0]);
    await fetch('/upload/somedata', {method: "POST", body: formData});    
<input type="file" onchange="saveFile(this)" >
  • In server side you can read original file name (and other info) which is automatically included to request.
  • You do NOT need to set header “Content-Type” to “multipart/form-data” browser will set it automatically
  • This solutions should work on all major browsers.

Here is more developed snippet with error handling, timeout and additional json sending

async function saveFile(inp) 
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user));  
    const ctrl = new AbortController() // timeout
    setTimeout(() => ctrl.abort(), 50000);

    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
<input type="file" onchange="saveFile(this)" >
Before selecting the file Open chrome console > network tab to see the request details.
<small>Because in this example we send request to  the response code will be 404 ofcourse...</small>

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →