简体   繁体   English

使用 Ajax XMLHttpRequest 上传文件

[英]Upload file with Ajax XMLHttpRequest

I am trying to send file with XMLHttpRequest with this code.我正在尝试使用此代码发送带有 XMLHttpRequest 的文件。

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我收到此错误: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;没有xhr.file = file;这样的东西。 ; ; the file object is not supposed to be attached this way.文件 object 不应该以这种方式附加。
  2. xhr.send(file) doesn't send the file. xhr.send(file)不发送文件。 You have to use the FormData object to wrap the file into a multipart/form-data post data object:您必须使用FormData object 将文件包装到multipart/form-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).之后,可以在$_FILES['thefile']中访问该文件(如果您使用的是 PHP)。

Remember, MDC and Mozilla Hack demos are your best friends.请记住, MDCMozilla Hack 演示是您最好的朋友。

EDIT : The (2) above was incorrect.编辑:上面的(2)是不正确的。 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 PHPhere .此处阅读如何在 PHP 中获取原始帖子数据。

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM