简体   繁体   English

上传文件XMLHttpRequest不起作用

[英]Upload file XMLHttpRequest not working

I am trying to upload file with ajax it does not work for some reason, can you see what's up? 我正在尝试使用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>

When I browse to the file and click submit I get error 当我浏览到文件并单击提交时,出现错误

According to the error, you need to create a myForm variable before you use it. 根据错误,需要使用创建myForm变量。

However, your larger problem is that one can't upload files with AJAX alone. 然而,你的更大的问题是, 一个人不能单用AJAX上传文件。 Try using a library like SWFupload . 尝试使用SWFupload之类的库。

If you don't want to use Flash or another plugin, you'll need to skip the AJAX and work straight with POST . 如果您不想使用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>

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

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