gpt4 book ai didi

php - 使用 XMLHttprequest 上传多个文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:44:43 25 4
gpt4 key购买 nike

我正在尝试制作一个以百分比表示进度的异步文件上传表单。我认为这可能适用于 FormData 对象,但我认为该帖子不起作用。当我提交时没有任何反应。我已经检查过,没有错误,它在没有 javascript 的情况下也能工作,所以 PHP 没问题,代码有什么根本性的错误吗?

  var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();

var fileInput = document.getElementById('file');
var data = new FormData();

for(var i = 0; i < fileInput.files.length; ++i){
data.append('file[]',fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress',function(event){
if(event.lengthComputable){

var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');

while (progress.hasChildNones()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});

request.upload.addEventListener('load',function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error',function(event){
alert("failed");

});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
};

window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});

html:

<div id = "upload_progress"></div>

<form id="form" action="" method="post" enctype="multipart/form-data">
<input id="file" name="file[]" type="file" multiple /><br>
<input type="submit" name="send" id ="submit" value="send">
</form>

和upload.php

if(!empty($_FILES['file'])){
foreach ($_FILES['file']['name'] as $key => $name) {
move_uploaded_file($_FILES['file']['tmp_name'][$key],"myfiles/$name");
}
}

最佳答案

您忘记了 javascript 代码中最重要的一行:

request.send(data);

在此之后:

request.setRequestHeader('Cache-Control','no-cache');

关于php - 使用 XMLHttprequest 上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14666765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com