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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.