Skip to main content

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

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. 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

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex