开发者

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 i开发者_C百科s 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.


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


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.


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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜