12

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.

lisak
  • 21,611
  • 40
  • 152
  • 243

4 Answers4

2

You can manually generate the MIME data for the upload from the HTML5 file data read using FileReader or similar APIs. Check out: https://github.com/coolaj86/html5-formdata . This will do more or less that, although it depends on getAsBinary() -- changing it to also be able to use FileReader and readAsBinaryString() would probably be more cross-browser-compatible.

Note that this still won't work at all in IE7/8, and as others have said, there is no way to do it without resorting to Flash or iframes. That being said, if you're using File, presumably you don't care about IE7 or IE8 anyway...

Gijs
  • 5,201
  • 1
  • 27
  • 42
  • Thanks man, good to know about this. I wouldn't use it if I didn't have it backed by flash. And you're right, I don't care about IE users, after 5 years on Linux... Sometimes I just tell them to run my app with another browser... – lisak Jun 05 '11 at 19:16
0

How can I upload files asynchronously?

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.

* edit since I am getting comments on it *

Yes it is possible- http://caniuse.com/xhr2 - theres no IE support below 10 though..

Heres a tutorial:

http://www.html5rocks.com/en/tutorials/file/xhr2/

http://www.profilepicture.co.uk/ajax-file-upload-xmlhttprequest-level-2/

Community
  • 1
  • 1
Alex
  • 5,674
  • 7
  • 42
  • 65
  • sorry, I'm asking if this way is possible. It works with xhr.send(formData); to have it resolve to xhr.send(file) is afaik just a matter of setting it up properly. I just can't figure out how, it's very hard to find it when debugging it. – lisak May 24 '11 at 11:13
  • yes true. S0 far i know, with ajax you cannot upload files. You can however show user that it is being done in ajaxy way, by either using iframe or flash. – codingbbq May 26 '11 at 06:55
  • You can with the Formdata, as well as with file, like lisa is trying to do, but jQuery doesnt support it off the top of its head I believe. Heres an example even: http://hacks.mozilla.org/2009/06/xhr-progress-and-richer-file-uploading-feedback/ – Alex May 26 '11 at 07:29
  • This (and the linked question) is misleading, you can upload files via ajax/xhr2 - depending on browser support of course – Pete Mitchell Feb 07 '13 at 10:49
0

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.

kristopolous
  • 1,768
  • 2
  • 16
  • 24
  • Please do some reading instead of spreading your knowledge ... http://www.w3.org/TR/2011/WD-html5-20110525/ http://www.w3.org/TR/XMLHttpRequest2/ http://www.w3.org/TR/FileAPI/ – lisak May 31 '11 at 19:27
  • Awesome! I didn't know about these. I was referring to the attacks you can see here http://bit.ly/mmKsKj and the advisories here http://bit.ly/igcrvH . Many w3c recommendations never get implemented or then get legitimately removed after flaws are exposed: http://mzl.la/fBAMxD . So although these drafts exist, I think the history of vulnerabilities with specific regard to this functionality must be taken into consideration as to whether this feature can be relied upon or will be implemented; which is why I gave specific deference to the browser groups and not the w3c. – kristopolous Jun 01 '11 at 19:43
  • I'm afraid I downvoted this because it is not accurate. Indeed, XHR2, FormData, File, FileReader and similar APIs have been implemented for some time now by Chrome, Firefox and even IE9/10, and still rely on user choice for files. In particular, when the user has to explicitly select the file, there is no real security vulnerability added by enabling direct access, rather than forcing web developers to jump through the hoop of uploading a file to the server, before being able to read it on the client side. – Gijs Jun 05 '11 at 19:11
  • Although I agree with you in theory, the innovation of attacks always amazes me and it would be a travesty to rely on the shiny new features of a technology that has a very strong history of being legitimately crippled only to find out, much to your amazement, that the clear pattern continues. – kristopolous Jun 06 '11 at 19:34
0

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):

  1. For IE6-8, Opera, older versions of other browsers you get the file as you normally do with regular form-base uploads.

  2. 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 :)

Timo
  • 3,335
  • 30
  • 25
  • 2
    Timo, I can create such an uploader in a few hours, exactly according to my needs. I think the biggest problem of programmers is that they need some piece of code and the first thing to do is google around, searching for solutions of others :-) I understand that in case of some generic libraries providing low level support. But not in case of file uploader. After all, you spend more time by reverse engineering when it comes to problems, that if you created by yourself... :-) – lisak Jun 02 '11 at 09:22
  • Really? Well, I'm not that much javascript guru, that I could. Most definitely not something that works reasonably well across different browsers. But I suppose if you really know exactly what your doing, coughing up 683 lines of javascript isn't that big of a deal (including comments). Anyhow I fail to see how the infra to enable ajax uploads is not low level and why would I need to touch that stuff on any project. I suppose YMMV when considering what constitutes "generic library providing low level support". – Timo Jun 05 '11 at 08:34
  • @Sloin I totally disagree. If you look at the source of something like https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js ex. line 62 (today at least :P ) you can see how much crap you have to wade through to make this stuff compatible. – mraaroncruz Feb 09 '12 at 12:39