开发者

Upload file with Ajax XMLHttpRequest

开发者 https://www.devze.com 2023-03-10 07:58 出处:网络
I am trying to send file with XMLHttpRequest with this code. var url= "http://localhost:80/....";

I am trying to send file with XMLHttpRequest with this code.

var url= "http://localhost:80/....";
$(document).ready开发者_高级运维(function(){
    document.getElementById('upload').addEventListener('change', function(e) {
        var file = this.files[0];
        var xhr = new XMLHttpRequest();
        xhr.file = file; // not necessary if you create scopes like this
        xhr.addEventListener('progress', function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
        }, false);
        if ( xhr.upload ) {
            xhr.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
            };
        }
        xhr.onreadystatechange = function(e) {
            if ( 4 == this.readyState ) {
                console.log(['xhr upload complete', e]);
            }
        };
        xhr.open('post', url, true);
        xhr.setRequestHeader("Content-Type","multipart/form-data");
        xhr.send(file);
    }, false);
});

I get this error: T

The request was rejected because no multipart boundary was found.

What am I doing wrong?


  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.


A more extended answer:

let formData = new FormData();
formData.append("fileName", audioBlob);

$.ajax({
    "url": "https://myserver.com/upload",
    "method": "POST",
    "headers": {
        "API-Key": "myApiKey",
    },
    "async":        true,
    "crossDomain":  true,
    "processData":  false,
    "contentType":  false,
    "mimeType":     "multipart/form-data",
    "data":         formData
}).done(function(response){

    console.log(response);

});
0

精彩评论

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