12

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.

2
  • 1
    I found a similar question here: stackoverflow.com/questions/2320069/jquery-ajax-file-upload Commented Nov 20, 2012 at 22:38
  • I cannot use specify the action in the form '<form action="upload.php" method="post" enctype="multipart/form-data">' as there can be multiple actions, depending on user input. So I have a 'click' action on the upload button, which determines the type of input we got from the user and redirect accordingly. We did have this earlier and it was working, but now the requirement changed to redirect to different url/function depending on user input. Commented Nov 20, 2012 at 22:55

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This answer looks useful too: stackoverflow.com/questions/166221/…
Thanks Danijar. That solved my problem. Looking forward to IE10
You can send a file to server using blob data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.