上传文件XMLHttpRequest不起作用

时间:2012-10-18 22:01:48

标签: javascript jquery ajax file-upload xmlhttprequest

我正在尝试使用ajax上传文件但由于某些原因它无法正常工作,你能看到什么了吗?

     function upload(myform)

     var file = this.files[0];
     var formData = new FormData();
     formData.append("material_file", document.getElementById("myfile"));

    xmlhttp = new XMLHttpRequest();
    xmlhttp.addEventListener('progress', function(e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
        console.log('xmlhttp progress: ' + (Math.floor(done/total*1000)/10) + '%');
    }, false);
    if ( xmlhttp.upload ) {
        xmlhttp.upload.onprogress = function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xmlhttp.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
        };
    }
    xmlhttp.onreadystatechange = function(e) {
        if ( 4 == this.readyState ) {
            console.log(['xmlhttp upload complete', e]);
        }
    };
    xmlhttp.open('post', process_pdf.php, true);
    xmlhttp.setRequestHeader("Content-Type","multipart/form-data");
    xmlhttp.send(formData);
     }


<form onsubmit="upload(this)">
     <input type="file" name="myfile">
</form>

当我浏览到该文件并单击“提交时,我收到错误

1 个答案:

答案 0 :(得分:0)

根据错误,您需要在之前创建myForm变量

但是,更大的问题是one can't upload files with AJAX alone.尝试使用像SWFupload这样的库。

如果您不想使用Flash或其他插件,则需要跳过AJAX并直接使用POST

<form method="post" enctype="multipart/form-data" action="/PATH/TO FILE">
    <input type="file" name="myfile">
    <input type="submit" value="upload file">
</form>