【问题标题】:Upload file XMLHttpRequest not working上传文件 XMLHttpRequest 不起作用
【发布时间】:2012-10-19 06:35:24
【问题描述】:

我正在尝试使用 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>

当我浏览到文件并单击提交时出现错误

【问题讨论】:

    标签: javascript jquery ajax file-upload xmlhttprequest


    【解决方案1】:

    根据报错,需要在使用前创建一个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>
    

    【讨论】:

    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2010-12-27
    • 2013-06-12
    • 2014-01-09
    • 2018-12-01
    • 2013-03-17
    • 2013-12-09
    相关资源
    最近更新 更多