使用Ajax XmlHttpRequest上传文件

Sed*_*şar 57 javascript ajax jquery file-upload xmlhttprequest

嗨,我正在尝试使用此代码发送带有xmlhttprequest的文件.

<script>
    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);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

但我得到了这个错误:请求被拒绝,因为没有找到多部分边界帮助我..

tim*_*eam 96

  1. 没有这样的事情xhr.file = file;; 文件对象不应该以这种方式附加.
  2. xhr.send(file)不发送文件.您必须使用该FormData对象将文件包装到multipart/form-datapost数据对象中:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    
    Run Code Online (Sandbox Code Playgroud)

之后,可以访问该文件$_FILES['thefile'](如果您使用的是PHP).

请记住,MDCMozilla Hack演示是您最好的朋友.

编辑:上面的(2)是不正确的.它确实发送文件,但它会将其作为原始发布数据发送.这意味着您必须自己在服务器上解析它(而且通常不可能,取决于服务器配置).了解如何在PHP中获得的原始数据后这里.

  • xhr.send(file)基于XHR2,它是XMLHttpRequest对象的新版本,仅在某些浏览器中可用. (5认同)
  • 此方法至少需要IE10或Android 3.0. (2认同)