Sunday, April 8, 2012

Is it possible to upload file via $.ajax(options) or xhr.send(file) only?



I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working.





Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than







var xhr = new XMLHttpRequest();

xhr.setRequestHeader("Cache-Control", "no-cache");

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

xhr.setRequestHeader("X-File-Name", file.name);

xhr.send(file);







Which doesn't return Promise that I can use in the recursion function.





My code is like this :







startUpload: function() {

var that = this;

that.recurseSend(that.queue);

},



_initProgressListener: function (options, file) {

var that = this;

var xhr = $.ajaxSettings.xhr();

options.contentType = 'multipart/form-data';

options.processData = false;

options.type = 'POST';

// WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails



/* THIS WOULD WORK

var formData = new FormData();

formData.append('file', file);

options.data = formData;

*/



if (xhr.upload && xhr.upload.addEventListener) {

xhr.upload.addEventListener('progress', function (e) {

that._onProgress(e, file);

}, false);

options.xhr = function () {

return xhr;

};

}

},



recurseSend: function (queue) {

var file = queue.pop();

if(file != undefined) {

var that = this;

var options = that.options;

that._initProgressListener(options, file);



var send = function() {

jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {

that._onDone(result, textStatus, jqXHR, file);

queue.stats['successful_uploads']++;

}).fail(function(jqXHR, textStatus, errorThrown) {

that._onFail(jqXHR, textStatus, errorThrown, file);

queue.stats['upload_errors']++;

}).always(function(result, textStatus, jqXHR) {

that._onAlways(result, textStatus, jqXHR, file);

queue.stats['files_queued']--;

that.recurseSend(queue);

});

return jqXHR;

};



this._beforeSend(file);

return send();

}

},







To make it short, $.ajax(options) resolves into xhr.send(formData) if options.data = FormData but how do I make it resolve into xhr.send(file) ?





EDITED: I was playing with it and if I set options.data = file; then $.ajax(options) executes xhr.send(theFile); but with error Error: INVALID_STATE_ERR: DOM Exception 11





and the request is sent as POST multipart/form-data request, but without the multipart body with file in it





And if I put it into options.data = {file: file}; it is serialized no matter if processData property is set to true or not.



Source: Tips4all

4 comments:

  1. How can I upload files asynchronously with JQuery?

    And hey! Bam. Instant expert.

    It seems you can't do this without going through an iFrame. There seem to be working snippets in the answer i linked, and several plugins that do it for you.

    ReplyDelete
  2. Cross browser support for Ajax (like) file upload with progress is damn near impossible.

    I usually use SWFUpload.

    I know, it's flash, but it works. The only browsers that it will always fail for are Apples mobile browsers, but they don't support uploads anyway.

    ReplyDelete
  3. I my self have used valums ajax uploader. You can get it from here:
    http://valums.com/ajax-upload/. It works pretty nicely. I don't know the exact implementation details, but here's a very short description:

    "This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere."

    So it sounds like its very close to what you want. Here's another bit of info describing the way it works from the servers point of view (from server/readme.txt):


    For IE6-8, Opera, older versions of other browsers you get the file as
    you normally do with regular form-base uploads.
    For browsers which upload file with progress bar, you will need to get the raw
    post data and write it to the file.


    So it requires special handling on the server side. Luckily it comes with several reference server side implementations (perl, php and java) so that shouldn't be too much of hassle. Happy ajax uploading :)

    ReplyDelete
  4. Whenever you are dealing with uploading arbitrary data from a users machine, the answer is usually "no, and if you can, that's a bug".

    This strikes me as something that would fall under the umbrella of security violations. You can't change the value of the file input control or do many other things to it including read the true path of the file or its contents. Furthermore, on some platforms you don't have even the file size (IE, I'm looking at you) without some security dialog popping up (via an activex control). Given all of these problems I would probably be tempted to say that even if you did find a solution, it would be potentially viewed as a bug in the future and removed or changed.

    In other words, I don't think it's a safe thing to do unless you find a reputable source explicitly supporting it ... like the chromium dev blog.

    ReplyDelete