jQuery Ajax File Upload


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.

7/5/2019 10:09:31 AM

Accepted Answer

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.

3/23/2020 2:40:26 PM

Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:

Using HTML5 file uploads with AJAX and jQuery

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() {
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 =;
    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;

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.

Here is more information: - How to upload a file using jQuery.ajax and FormData - Uploading files via jQuery, object FormData is provided and no file name, GET request

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

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"/> 


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="//"></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";

An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.

For details see: Answer to question jQuery Upload Progress and AJAX file upload.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]