我正在尝试使用 drag and drop plugin在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 访问该文件。
最佳答案
尝试使用 FormData
而不是 xhr
:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
您可以使用此数组
访问您的文件:
<?php var_dump($_FILES["thefile"]); ?>
关于php - 使用 XMLHttpRequest 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10879841/