使用XMLHttpRequest上传文件

时间:2012-06-04 10:29:26

标签: php ajax file-upload xmlhttprequest

我正在尝试使用javascript中的drag and drop plugin来使用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访问该文件。

1 个答案:

答案 0 :(得分:8)

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

相关问题