By Sergio del Amo

2008-10-03 10:22:17 8 Comments

I would like to upload a file asynchronously with jQuery.

$(document).ready(function () {
    $("#uploadbutton").click(function () {
        var filename = $("#file").val();

            type: "POST",
            url: "",
            enctype: 'multipart/form-data',
            data: {
                file: filename
            success: function () {
                alert("Data Uploaded: ");
<script src=""></script>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>

Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?


@Oli 2008-10-03 10:41:31

2019 Update: It still depends on the browsers your demographic uses.

An important thing to understand with the "new" HTML5 file API is that it wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average propensity toward older versions of Windows, you might not have access to it.

As of 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (e.g., this is a B2B tool, or something you're delivering for training) that number can skyrocket. In 2016, I dealt with a company using IE8 on over 60% of their machines.

It's 2019 as of this edit, almost 11 years after my initial answer. IE9 and lower are globally around the 1% mark but there are still clusters of higher usage.

The important take-away from this —whatever the feature— is, check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client. caniuse is a useful tool but note where they get their demographics from. They may not align with yours. This is never truer than enterprise environments.

My answer from 2008 follows.

However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.

It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.

If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.

Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...

@meleyal 2011-03-25 10:05:26

For the record it's now possible to do pure AJAX file uploads if the browser supports the File API -

@Brett Caswell 2015-10-29 14:54:52

this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.

@Oli 2015-10-29 15:34:04

@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.

@Diego Vinícius 2020-02-28 15:06:49

What if using promises which ajax and checking if the file is valid and well saved in your backend, so you can use some animation in front while user is navigating thought your page.

You can even make it paralel upload or stacking with recursive approach

@Kamil Kiełczewski 2019-07-05 10:31:57


async function saveFile() 
    let formData = new FormData();           
    formData.append("file", file.files[0]);
    await fetch('', {method: "POST", body: formData});    
    alert("Data Uploaded: ");
<input type="file" id="file" name="file" size="10"/>
<input type="button" value="Upload" onclick="saveFile()"/>

The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server). Here is more developed example with err handling and json adding

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));  
    try {
       let r = await fetch('/upload/image', {method: "POST", body: formData}); 
       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>

@Erick Langford Xenes 2015-11-03 20:47:25

This is my solution.

<form enctype="multipart/form-data">    

    <div class="form-group">
        <label class="control-label col-md-2" for="apta_Description">Description</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">

    <input name="file" type="file" />
    <input type="button" value="Upload" />

and the js


    $(':button').click(function () {
        var formData = new FormData($('form')[0]);
            url: '@Url.Action("Save", "Home")',  
            type: 'POST',                
            success: completeHandler,
            data: formData,
            cache: false,
            contentType: false,
            processData: false

    function completeHandler() {


public ActionResult Save(string apta_Description, HttpPostedFileBase file)

@Zero3 2015-12-19 18:06:46

You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.

@nonchip 2016-01-06 22:27:47

so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.

@Alister 2018-08-17 11:47:19

A modern approach without Jquery is to use the FileList object you get back from <input type="file"> when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.

// The input DOM element // <input type="file">
const inputElement = document.querySelector('input[type=file]');

// Listen for a file submit from user
inputElement.addEventListener('change', () => {
    const data = new FormData();
    data.append('file', inputElement.files[0]);
    data.append('imageName', 'flower');

    // You can then post it to your server.
    // Fetch can accept an object of type FormData on its  body
    fetch('/uploadImage', {
        method: 'POST',
        body: data

@Marco Demaio 2019-01-16 16:31:35

Apparently not supported on IE

@Topstar5 2019-04-08 12:14:53

You can use the following code.

async: false(true)

@kvz 2018-12-21 09:00:10

You could also consider using something like

It does file uploading without navigating away from the page and offers a few bonuses like drag & drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram. It's open source and does not rely on jQuery/React/Angular/Vue, but can be used with it. Disclaimer: as its creator I'm biased ;)

@lat94 2018-02-21 14:41:37

It is an old question, but still has no answer correct answer, so:

Have you tried jQuery-File-Upload?

Here is an example from the link above that might solve your problem:

    add: function (e, data) {
        var that = this;
        $.getJSON('/example/url', function (result) {
            data.formData = result; // e.g. {id: 123}
      , e, data);

@olanod 2012-01-06 13:34:48

With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.


<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />

First, you can do some validation if you want. For example, in the .on('change') event of the file:

$(':file').on('change', function () {
  var file = this.files[0];

  if (file.size > 1024) {
    alert('max upload size is 1k');

  // Also see .name, .type

Now the $.ajax() submit with the button's click:

$(':button').on('click', function () {
    // Your server script to process the upload
    url: 'upload.php',
    type: 'POST',

    // Form data
    data: new FormData($('form')[0]),

    // Tell jQuery not to process data or worry about content-type
    // You *must* include these options!
    cache: false,
    contentType: false,
    processData: false,

    // Custom XMLHttpRequest
    xhr: function () {
      var myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        // For handling the progress of the upload
        myXhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) {
              value: e.loaded,
        }, false);
      return myXhr;

As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.

@olanod 2012-05-13 19:49:32

@Silver89 if you mean to return data from the server script you set in the url setting('upload.php' in this case), the response will be whatever you print or echo in that script. Then you can do whatever you want with the data. Check the ajaxComplete and similar functions in jQuery Docs

@Dan 2012-06-05 04:26:24

I have the file part working ... but can you include text fields in this as well? This doesn't seem to with var formData = new FormData($('form')[0]); or serialize() ?

@olanod 2012-06-05 10:57:03

with "new FormData($('form')[0]);" it should work, your text field has a name? use print_r on $_POST to make sure data is there, check the response on the network monitor(chrome) to see the raw response.

@Alessandro Cosentino 2012-11-02 13:41:48

Can I then use $_FILES in the upload.php?

@Tyler 2013-01-02 16:33:44

This should work in Internet Explorer but only Version 10. (

@Shumii 2013-06-01 05:29:32

Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.

@incarnate 2013-09-12 13:26:28

It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.

@Karthik Ravichandran 2018-11-14 12:42:19

You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.

var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2'); 
formData.append('file', $('input[type=file]')[0].files[0]);

    url: 'post back url',
    data: formData,
// other attributes of AJAX

Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here

@Supun Kavinda 2018-10-05 10:45:28

For PHP, look for


    <title>Image Upload with AJAX, PHP and MYSQL</title>
<form onsubmit="submitForm(event);">
    <input type="file" name="image" id="image-selecter" accept="image/*">
    <input type="submit" name="submit" value="Upload Image">
<div id="uploading-text" style="display:none;">Uploading...</div>
<img id="preview">


var previewImage = document.getElementById("preview"),  
    uploadingText = document.getElementById("uploading-text");

function submitForm(event) {
    // prevent default form submission

function uploadImage() {
    var imageSelecter = document.getElementById("image-selecter"),
        file = imageSelecter.files[0];
    if (!file) 
        return alert("Please select a file");
    // clear the previous image
    // show uploading text = "block";
    // create form data and append the file
    var formData = new FormData();
    formData.append("image", file);
    // do the ajax part
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            var json = JSON.parse(this.responseText);
            if (!json || json.status !== true) 
                return uploadError(json.error);

    }"POST", "upload.php", true);
    ajax.send(formData); // send the form data


$host = 'localhost';
$user = 'user';
$password = 'password';
$database = 'database';
$mysqli = new mysqli($host, $user, $password, $database);

 try {
    if (empty($_FILES['image'])) {
        throw new Exception('Image file is missing');
    $image = $_FILES['image'];
    // check INI error
    if ($image['error'] !== 0) {
        if ($image['error'] === 1) 
            throw new Exception('Max upload size exceeded');

        throw new Exception('Image uploading error: INI Error');
    // check if the file exists
    if (!file_exists($image['tmp_name']))
        throw new Exception('Image file is missing in the server');
    $maxFileSize = 2 * 10e6; // in bytes
    if ($image['size'] > $maxFileSize)
        throw new Exception('Max size limit exceeded'); 
    // check if uploaded file is an image
    $imageData = getimagesize($image['tmp_name']);
    if (!$imageData) 
        throw new Exception('Invalid image');
    $mimeType = $imageData['mime'];
    // validate mime type
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($mimeType, $allowedMimeTypes)) 
        throw new Exception('Only JPEG, PNG and GIFs are allowed');

    // nice! it's a valid image
    // get file extension (ex: jpg, png) not (.jpg)
    $fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
    // create random name for your image
    $fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
    // Create the path starting from DOCUMENT ROOT of your website
    $path = '/examples/image-upload/images/' . $fileName;
    // file path in the computer - where to save it 
    $destination = $_SERVER['DOCUMENT_ROOT'] . $path;

    if (!move_uploaded_file($image['tmp_name'], $destination))
        throw new Exception('Error in moving the uploaded file');

    // create the url
    $protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
    $domain = $protocol . $_SERVER['SERVER_NAME'];
    $url = $domain . $path;
    $stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
    if (
        $stmt &&
        $stmt -> bind_param('s', $url) &&
        $stmt -> execute()
    ) {
                    'status' => true,
                    'url' => $url
    } else 
        throw new Exception('Error in saving into the database');

} catch (Exception $e) {
        array (
            'status' => false,
            'error' => $e -> getMessage()

@Joe Clinton 2018-08-29 19:51:59

You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -

  1. ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
  2. ASP.NET MVC based Multiple File Upload made in jQuery

The server side language is C# but you can do some modification for making it work with other language like PHP.

File Upload ASP.NET Core MVC:

In the View create file upload control in html:

<form method="post" asp-action="Add" enctype="multipart/form-data">
    <input type="file" multiple name="mediaUpload" />
    <button type="submit">Submit</button>

Now create action method in your controller:

public async Task<IActionResult> Add(IFormFile[] mediaUpload)
    //looping through all the files
    foreach (IFormFile file in mediaUpload)
        //saving the files
        string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path"); 
        using (var stream = new FileStream(path, FileMode.Create))
            await file.CopyToAsync(stream);

hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:

private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
    hostingEnvironment = environment;

@Alireza 2018-03-12 12:32:13

Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload from root of your website, this code should work for you:

const asyncFileUpload = () => {
  const fileInput = document.getElementById("file");
  const file = fileInput.files[0];
  const uri = "/upload";
  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = e => {
    const percentage = e.loaded /;
  xhr.onreadystatechange = e => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("file uploaded");
  };"POST", uri, true);
  <input type="file" id="file" name="file" size="10" />
  <input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />

Also some further information about XMLHttpReques:

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

For more details, you can continue reading here...

@404 2014-08-25 14:17:29

Wrapping up for future readers.

Asynchronous File Upload

With HTML5

You can upload files with jQuery using the $.ajax() method if FormData and the File API are supported (both HTML5 features).

You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).

  url: 'file/destination.html', 
  type: 'POST',
  data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
  processData: false,
  contentType: false                    // Using FormData, no need to process data.
  console.log("Success: Files sent!");
  console.log("An error occurred, the files couldn't be sent!");

For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".


When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.

It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.

If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.

In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax() method like this:

  url: 'file/destination.html', 
  type: 'POST',
  // Set the transport to use (iframe means to use Bifröst)
  // and the expected data type (json in this case).
  dataType: 'iframe json',                                
  fileInputs: $('input[type="file"]'),  // The file inputs containing the files to send.
  data: { msg: 'Some extra data you might need.'}
  console.log("Success: Files sent!");
  console.log("An error occurred, the files couldn't be sent!");


Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.

@ash 2015-08-18 22:44:55

One thing to note, based on the documentation: you should also send contentType: false. When I didn't send this with chrome the form content type was invalidated by jQuery.

@Zero3 2015-12-19 18:10:32

Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the .done() and .fail() callbacks. Also, an example without the use of FormData and a list of pro/cons would be awesome.

@candlejack 2016-12-25 23:15:44

I got this error: TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.

@Mattias 2008-10-03 10:36:38

Note: This answer is outdated, it is now possible to upload files using XHR.

You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.

@Mattias 2008-10-03 17:21:49

Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.

@Alleo 2011-11-03 18:57:48

Small remark: in latest versions of chrome and firefox it is possible,…

@Radmation 2018-09-07 20:43:23

Not supported in IE9 and less

@ArtisticPhoenix 2014-06-26 04:43:12

The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.

That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...

<form target="iframe" action="" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />

<iframe name="iframe" id="iframe" style="display:none" ></iframe>

You can also read the contents of the iframe onLoad for server errors or success responses and then output that to user.

Chrome, iFrames, and onLoad

-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading

Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.

The only solution that I found works for Chrome was to use a cookie.

To do that basically when the upload/download is started:

  • [Client Side] Start an interval to look for the existence of a cookie
  • [Server Side] Do whatever you need to with the file data
  • [Server Side] Set cookie for client side interval
  • [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.

Using a cookie for this is ugly but it works.

I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here

The same basic principal applies to uploading, as well.

To use the downloader ( include the JS, obviously )

     "onComplete" : function(){
          $('#uiBlocker').css('display', 'none'); //hide ui blocker on complete

 $('somebuttion').click( function(){
      $('#uiBlocker').css('display', 'block'); //block the UI
      $('body').iDownloader('download', 'htttp://');

And on the server side, just before transferring the file data, create the cookie

 setcookie('iDownloader', true, time() + 30, "/");

The plugin will see the cookie, and then trigger the onComplete callback.

@Yevgeniy Afanasyev 2015-01-05 22:45:43

I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.

@Prakhar Mishra 2016-06-28 11:19:33

Well, I guess the reason would be to show some progress info while uploading.

@BlackBeard 2018-05-21 10:14:35

You can use newer Fetch API by JavaScript. Like this:

function uploadButtonCLicked(){
    var input = document.querySelector('input[type="file"]')

    fetch('/url', {
      method: 'POST',
      body: input.files[0]
    }).then(res => res.json())   // you can do something with response
      .catch(error => console.error('Error:', error))
      .then(response => console.log('Success:', response));

Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..) asynchronously.

@Allende 2015-07-08 17:59:34

Look for Handling the upload process for a file, asynchronously in here:

Sample from the link

if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
?><!DOCTYPE html>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

  "POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); // handle response.
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {

            dropzone.ondrop = function(event) {

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>

@Zayn Ali 2014-08-08 02:59:30

You can upload simply with jQuery .ajax().


<form id="upload-form">
        <label for="file">File:</label>
        <input type="file" id="file" name="file" />
        <progress class="progress" value="0" max="100"></progress>
    <hr />
    <input type="submit" value="Submit" />


.progress { display: none; }


$(document).ready(function(ev) {
    $("#upload-form").on('submit', (function(ev) {
            xhr: function() {
                var progress = $('.progress'),
                    xhr = $.ajaxSettings.xhr();


                xhr.upload.onprogress = function(ev) {
                    if (ev.lengthComputable) {
                        var percentComplete = parseInt((ev.loaded / * 100);
                        if (percentComplete === 100) {

                return xhr;
            url: 'upload.php',
            type: 'POST',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            success: function(data, status, xhr) {
                // ...
            error: function(xhr, status, error) {
                // ...

@pixxaar 2008-11-21 16:38:06

I recommend using the Fine Uploader plugin for this purpose. Your JavaScript code would be:

$(document).ready(function() {
    action: "",
    onComplete: function(response){
      alert( "server response: " + response);

@Lorenzo Manucci 2011-06-22 09:35:43

It uses JSON - so for PHP old version it will be non possible use.

@Simon East 2012-07-01 01:43:50

Newer URL for version 2 is now

@Trantor Liu 2012-07-23 12:02:24

"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.

@Darren Cook 2013-11-28 02:08:27

@Kerry Do you have a link regarding MIT license? The latest version (Version 4) appears to be GPL3 only, no LGPL: Version 2 mentions LGPL:

@Kerry Jones 2013-11-28 14:16:03

@DarrenCook Yeah, I noticed that earlier this year. I have a downloaded copy of the old code, not as pretty, but it still has the old license, but not online.

@Ankan-Zerob 2014-05-27 20:44:35

@BryanLarsen You do not need to release the code if it is a website (or a SaaS solution), since you are not distributing the "binary", you do not need to distribute the code. Some resources :…

@Oli 2015-09-22 10:36:37

They have switched license again. it's a proprietary license that separately calls out commercial use, so unlike the GPL, there is no escape from licensing the latest version for commercial use. This is the last committed version available under GPL (Dec 2014).

@Ray Nicholus 2016-05-14 21:54:13

As of Fine Uploader 5.9.0, the library is now 100% Free Open Source Software and MIT licensed.

@MEAbid 2016-10-14 07:17:46

Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin,


var $bar   = $('.ProgressBar');
  dataType: 'json',

  beforeSend: function(xhr) {
    var percentVal = '0%';

  uploadProgress: function(event, position, total, percentComplete) {
    var percentVal = percentComplete + '%';

  success: function(response) {
    // Response

I hope it would be helpful

@Daniel Nyamasyo 2016-07-19 05:18:34

You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:

<from action="" id="formContent" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" size="10"/>
    <input id="uploadbutton" type="button" value="Upload"/>

The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.

$(document).ready(function () {

     var formdata = new FormData(this);

     url: "ajax_upload_image.php",
     type: "POST",
     data: formdata,
     contentType: false,
     cache: false,
     processData: false,
     success: function(){

     alert("successfully submitted");


View more details

@Siddhartha Chowdhury 2016-03-30 16:48:31

Here's just another solution of how to upload file (without any plugin)

Using simple Javascripts and AJAX (with progress-bar)

HTML part

<form id="upload_form" enctype="multipart/form-data" method="post">
    <input type="file" name="file1" id="file1"><br>
    <input type="button" value="Upload File" onclick="uploadFile()">
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>

JS part

function _(el){
    return document.getElementById(el);
function uploadFile(){
    var file = _("file1").files[0];
    // alert(" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);"POST", "file_upload_parser.php");
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of ";
    var percent = (event.loaded / * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
function completeHandler(event){
    _("status").innerHTML =;
    _("progressBar").value = 0;
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";

PHP part

$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
    echo "$fileName upload is complete";
} else {
    echo "move_uploaded_file function failed";

Here's the EXAMPLE application

@Vivek Aasaithambi 2015-07-28 13:39:10

var formData=new FormData();

    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    success:function(data){ }

You can use form data to post all your values including images.

@Gone Coding 2015-08-10 09:10:27

Note: cache: false is redundant on a POST request as POST never caches.

@candlejack 2016-12-25 23:28:42

@Vivek Aasaithambi, I got this error: TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.

@ashish 2014-06-23 08:18:49

To upload file asynchronously with Jquery use below steps:

step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.)) URL:

step 2 Add below scripts in the HTML files, which are already added to the project by running above package:




step 3 Write file upload control as per below code:

<input id="upload" name="upload" type="file" />

step 4 write a js method as uploadFile as below:

 function uploadFile(element) {
                dataType: 'json',
                url: '../DocumentUpload/upload',
                autoUpload: true,
                add: function (e, data) {           
                  // write code for implementing, while selecting a file. 
                  // data represents the file data. 
                  //below code triggers the action in mvc controller
                  data.formData =
                                     files: data.files[0]
                done: function (e, data) {          
                   // after file uploaded
                progress: function (e, data) {
                   // progress
                fail: function (e, data) {
                   //fail operation
                stop: function () {
                  code for cancel operation

step 5 In ready function call element file upload to initiate the process as per below:



step 6 Write MVC controller and Action as per below:

public class DocumentUploadController : Controller
        public JsonResult upload(ICollection<HttpPostedFileBase> files)
            bool result = false;

            if (files != null || files.Count > 0)
                    foreach (HttpPostedFileBase file in files)
                        if (file.ContentLength == 0)
                            throw new Exception("Zero length file!");                       
                            //code for saving a file

                catch (Exception)
                    result = false;

            return new JsonResult()



@tnt-rox 2014-06-23 18:50:47

Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder. Fiddle here

var reader = new FileReader();

        reader.onload = function(readerEvt) {
            var binaryString =;
            document.getElementById("base64textarea").value = btoa(binaryString);


Then to retrieve:"data:application/octet-stream;base64," + base64);

@Amit 2014-05-12 10:10:03

You can use

$(function() {
        height        : 30,
        swf           : '/uploadify/uploadify.swf',
        uploader      : '/uploadify/uploadify.php',
        width         : 120


@farnoush resa 2013-06-16 09:49:29

jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.

    'swf': '/public/js/uploadify.swf',
    'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
    'cancelImg': '/public/images/uploadify-cancel.png',
    'multi': true,
    'onQueueComplete': function (queueData) {
        // ...
    'onUploadStart': function (file) {
        // ...

I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:

$(document).ready(function () {
    $('#btn_Upload').live('click', AjaxFileUpload);

function AjaxFileUpload() {
    var fileInput = document.getElementById("#Uploader");
    var file = fileInput.files[0];
    var fd = new FormData();
    fd.append("files", file);
    var xhr = new XMLHttpRequest();"POST", 'Uploader.ashx');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
        else if (uploadResult == 'success')

@Ray Nicholus 2016-06-08 17:44:39

Uploadify has been dead for years. Not supported or maintained anymore.

@mpen 2013-02-17 09:34:41

You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
};'POST', '/upload', true);
xhr.setRequestHeader('X-FileName',; // Pass the filename along

@mpen 2013-04-03 15:35:09

@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: -- just click "view source". Essentially, inside the ondrop event you can do var file = e.dataTransfer.files[0]

@Andy 2017-10-31 06:55:18

Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.

@mpen 2017-10-31 16:20:17

@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.

@x-yuri 2020-07-04 12:09:33

I'm not sure it's a good idea to upload a file this way. Usually files are uploaded using multipart/form-data. And servers expect that they might be big. I mean if you upload a file this way, it'll most likely end up in memory no matter how big it is. With multipart/form-data it might be stored in a temporary file. But the idea is tempting :)

@mpen 2020-07-04 19:25:01

@x-yuri This method is better for sever-side handling. The entire body/payload can be streamed directly to a file or processed as it comes in. With multipart/form-data, it has to be parsed before the server can decide what to do with it.

@x-yuri 2020-07-04 21:12:59

Good point. Anyway, for completeness, uploading a file using multipart/form-data is not much harder.

@Techie 2013-01-25 11:03:28

I have been using the below script to upload images which happens to work fine.


<input id="file" type="file" name="file"/>
<div id="response"></div>


    var input = document.getElementById("file");
    var formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    input.addEventListener("change", function (evt) {
        var i = 0, len = this.files.length, img, reader, file;

        for ( ; i < len; i++ ) {
            file = this.files[i];

            if (!!file.type.match(/image.*/)) {
                if ( window.FileReader ) {
                    reader = new FileReader();
                    reader.onloadend = function (e) {
                        //showUploadedItem(, file.fileName);

                if (formdata) {
                    formdata.append("image", file);

                if (formdata) {
                    jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');

                        url: "upload.php",
                        type: "POST",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                         jQuery('div#response').html("Successfully uploaded");
                alert('Not a vaild image!');

    }, false);


I use response div to show the uploading animation and response after upload is done.

Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data as in the script.

At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST data.

Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.

@Mark 2013-09-22 20:49:45

-1 for using jQuery and not using it's selector engine and event handlers. addEventListener is not cross-browser.

@Mark 2013-11-23 16:14:22

Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.

@Thiago Negri 2014-01-27 13:57:18

@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.

@Pierre 2014-06-28 10:48:36

Still does not work in IE 9 and down. Allot of users still use those versions of IE.

@SamuraiJack 2015-05-23 05:23:07

Can someone please explain how can this be made to work in Do I use webmethod? If yes what would it look like?

Related Questions

Sponsored Content

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

43 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

66 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6964400 View
  • 8520 Score
  • 96 Answer
  • Tags:   javascript arrays

39 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

3 Answered Questions

15 Answered Questions

Sponsored Content