1

I am wondering why i can't upload a file in JQuery using the $.post() method?

Is there any way to tweak the request to be able to handle this?

$.post(url, { file: fileName, path: "/uploads" }, function (result) {});
some_bloody_fool
  • 4,605
  • 14
  • 37
  • 46

1 Answers1

6

I am wondering why i can't upload a file in JQuery using the $.post() method?

It's because in order to upload a file you need to use multipart/form-data protocol meaning that the request body needs to be presented in a completely different manner than standard form POST which is what jQuery uses: application/x-www-form-urlencoded (a key/value pairs separated by & in the POST body). Not to mention that in order to write the file contents in the request, you need to have access to, well, the file contents, which in javascript, as you know, is not the case at all.

But don't lose all hopes yet. In the future, with XmlHttpRequest2 and HTML5 you will be able to upload files using AJAX.

Until this future comes (which by the way should not be that far away, as soon as we have gotten rid of IE<=9) stick with what exists today which is: file uploading plugins that detect browsers capabilities and use XHR2 if the browser supports it and some other technology (such as hidden iframes or Flash if it doesn't) and relieve you from the burden of doing this manually yourself.

So go ahead, Google, and make a wishlist:

Then go ahead play with the demos, read the docs, pick one that suits your needs and try to put it into action in your site. If you encounter some specific problems don't hesitate to ask.

But unfortunately uploading files with $.post is a no-no for today.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928