使用XMLHttpRequest上传文件

3
我正在尝试使用JavaScript中的拖放插件来使用Ajax上传文件。
<script>
DnD.on('#drop-area', {

'drop': function (files, el) {
   el.firstChild.nodeValue = 'Drag some files here.';
   var names = [];
   [].forEach.call(files, function (file, i) {
      names.push(file.name + ' (' + file.size + ' bytes)');

   var xhr = new XMLHttpRequest();
   xhr.open('POST','upload.php');
   xhr.setRequestHeader("Content-type", "multipart/form-data"); 
   xhr.send(file);
   console.log(xhr.responseText);
});
document.querySelector('#dropped-files p i').firstChild.nodeValue = names.join(', ');
}
});
</script>

这里是upload.php:

<?php
print_r($_POST);
?>

基本上我还没有编写上传文件的脚本,因为我仍在思考如何访问通过JavaScript发送的数据。你能指导我接下来该怎么做吗?我该如何从upload.php访问文件。

2个回答

10
尝试使用FormData代替xhr:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);

你可以使用这个 array 访问你的文件:

<?php var_dump($_FILES["thefile"]); ?> 

更多信息请参见:http://www.w3schools.com/php/php_file_upload.asp


当我使用console.log(xhr.responseText)时,仍然看不到任何东西。 - user225269
你使用的是哪个网络浏览器?请注意,在IE中XMLHttpRequest不起作用。 - Afshin Mehrabani
我正在使用Chrome Canary。感谢您的所有帮助,但它仍然无法工作,似乎根本没有文件被发送。 - user225269
你是否尝试在JavaScript代码中使用FormData?回答已编辑,请再次检查。 - Afshin Mehrabani
有一些解决调试此问题的方案。首先启用您的PHP error_handling 并将其设置为 E_ALL,现在您可能会看到一些错误或警告。 如果这没有帮助,请参见此问题:http://stackoverflow.com/questions/5659340/ajax-uploading-a-file-html-5-php 在您的标头中(xhr请求中),添加 X-File-TypeX-File-Name,并在 xhr.open 的第三个参数中填写 true - Afshin Mehrabani

0

PHP 代码:

<?php
 if($_SERVER['REQUEST_METHOD'] == 'POST'){
   echo $_FILES['fileToUpload']['name'];
 }
?>

HTML代码:

<form method="post" enctype="multipart/form-data">
    <input id="file-to-upload" type="file" name="file-to-upload">
    <button id="btn-submit">upload</button>
</form>

JavaScript 代码:
document.querySelector('#btn-submit').addEventListener('click' , function(ev){
        ev.preventDefault();
        /**
         * formData() representing form fields
         * https://developer.mozilla.org/en-US/docs/Web/API/FormData
         */
        formData = new FormData(); 
        /**
         * fileToUpload [input file]
         * input file has property called [files] contain 1 or multiple files
         * i use one file so i get 0 index file => image.files[0]
         */
        fileToUpload = document.querySelector('#file-to-upload');
        formData.append('fileToUpload' , fileToUpload.files[0]);
        /**
         * XMLHttpRequest
         */
        var xhr = new XMLHttpRequest();
        xhr.open('POST' , 'page.php' , true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                console.log(this.responseText);
            }
        }
        xhr.send(formData);
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接