use*_*269 3 php ajax file-upload xmlhttprequest
我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)
这是upload.php:
<?php
print_r($_POST);
?>
Run Code Online (Sandbox Code Playgroud)
基本上我还没有编写脚本来上传文件,因为我还在弄清楚如何访问我通过JavaScript发送的数据.你能指导我下一步做什么吗?如何从upload.php访问该文件.
尝试使用FormData而不是xhr:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
Run Code Online (Sandbox Code Playgroud)
您可以使用以下方式访问您的文件array:
<?php var_dump($_FILES["thefile"]); ?>
Run Code Online (Sandbox Code Playgroud)
查看更多:http://www.w3schools.com/php/php_file_upload.asp