0

I am trying to upload file with ajax it does not work for some reason, can you see what's up?

     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

4

1 回答 1

0

根据报错,使用myForm需要先创建变量。

但是,您更大的问题是无法单独使用 AJAX 上传文件。 尝试使用类似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>
于 2012-10-18T22:14:21.390 回答