我从这里开始:https://www.raymondcamden.com/2013/10/01/MultiFile-Uploads-and-Multiple-Selects
我尝试第二个代码
在handleform中,我改变如下:
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'data_post.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
在我的data_post.php中是这样的:print_r($_POST);
我选择了一些图像并提交,结果是这样的空数组:
Array ( )
为什么结果为空?
答案 0 :(得分:1)
追加文件后,您必须发布表单数据
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response);
}
});
答案 1 :(得分:1)
这是一个有多个文件的PHP代码的AJAX解决方案 您可以将整个代码复制/粘贴到localhost或服务器进行测试。
<?php
if($_FILES) {
if( is_array($_FILES['img']['name']) ) {
foreach($_FILES['img']['name'] as $key => $value) {
// upload path is the same directory as this file
move_uploaded_file($_FILES["img"]["tmp_name"][$key], $_FILES['img']['name'][$key]);
}
}
// test output
echo "<pre>";
print_r($_FILES);
echo "</pre>";
die();
}
?>
<script>
// on document ready
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("handleForm").addEventListener("click",function() {
var formData = new FormData( document.getElementById("form") );
for(var i = 0; i < document.getElementById("img").files.length; i++) {
console.log(i)
formData.append("img[]",document.getElementById("img").files[i]);
}
var xhr = new XMLHttpRequest();
// here you can change empty URL to your file
xhr.open("POST", "");
xhr.send(formData);
});
});
</script>
<form action="" method="post" enctype="multipart/form-data" id="form">
<input type="file" name="img" id="img" multiple />
<div style="padding: 5px 10px; border: 1px solid black; cursor: pointer; display: inline-block" id="handleForm" >Send</div>
</form>