Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending files /file upload using ajax which works in IE9

I need to upload files using ajax which has to be supported in IE9. I was using FormData as mentioned here. My code looks like this:

var files = new FormData();
JQuery.each($('#file')[0].files, function (i, file) {
    files.append('file', file);
});

$.ajax({
    type: "POST",
    url: '/url',
    cache: false,
    contentType: false,
    processData: false,
    data: files,
    ...
});

This works fine in Safari and Firefox, but fails in IE9 as the FormData is not supported in IE9. I tried sending just as a file by setting:

data: $('#file')[0].files[0]
contentType: 'multipart/form-data'

This fails as the data is sent in url-encoded form and is cannot be parsed at the java side. Any help or pointer on how to solve this will be greatly appreciated. I need something that works across all browsers.

EDIT: I do not need any upload progress bar as the files are usually small. I do not need to upload multiple files. I just need a single file upload.

like image 944
Alice Avatar asked Nov 20 '12 22:11

Alice


People also ask

Can we upload file using AJAX?

Ajax file uploadsA JavaScript method must be coded to initiate the asynchronous Ajax based file upload; A component must exist on the server to handle the file upload and save the resource locally; The server must send a response to the browser indicating the JavaScript file upload was successful; and.

How upload file with jQuery Ajax in MVC?

Uploading Files in MVC using jQuery AJAX FormDataGo to File->New->Project. Give a suitable name to the Application. Click OK. As you can see in the above image, two files are sent to C# ActionMethod, and both will be uploaded now.


1 Answers

Unfortunately you cannot use Ajax (XMLHttpRequest in other words) for sending files, but you can implement a similar behavior using the <iframe/> with a <form method="post" enctype="multipart/form-data"/> that contains an <input type="file"/> which sends a user chosen file using the "natural" way. You can use javascript to call the form.submit() then poll that <iframe/> from parent document to check whether the file upload process is done.

jQuery has a lot of cool plugins for getting this job done, there is my favorite one, for example.

like image 142
Dan K.K. Avatar answered Sep 22 '22 08:09

Dan K.K.