利用fetch方法和FormData对象上传多张图片
formdata()对象可以序列化多张图片
<html><head><meta http-equiv="content-type" content="text/html;charset=UTF-8"/><title>测试fetch和formdata上传多张图片</title></head><body><div id="upload">//accept="image/*"意思只能是图片<input type="file" name="uploadImg" id="uploadInput" multiple accept="image/*"><input type="button" name="uploadBtn" value="上传"/></div><script>function uploadImages(){//获取上传图片框const imagesInput=document.getElementById('uploadInput'),//转换成数组形式images=Array.from(imagesInput.files);//创建formData()对象 const formData=new FormData();//将每个图片都添加到formData对象中images.forEach((image,index) => {//这里用'files[]'数组最好,因为后端获取时是$_FILES['files'],如果用image或其它的表示,后端可能无法获取到图片组formData.append('files[]',image);}); //利用fetch上传图片fetch("fetchUpload.php",{method:'post',body:formData}).then((response)=>{return response.json();}).then((data)=>{console.log('Success:',data);}).catch(error=>{console.log('上传图片错误:',error);});}let btn=document.getElementsByName('uploadBtn');btn[0].addEventListener('click',uploadImages);</script></body>
</html>
后端文件
<?php
//图片类型白名单
$allowedTypes=['image/jpeg','image/png','image/gif'];
//检查文件是否存在
if(isset($_FILES['files']))
{
//赋值给变更$files;后面的$files['name']的原型为$_FILES['files']['name'][i]$files=$_FILES['files'];$uploadStatus=[];for($i=0;$i<count($files['name']);$i++){$fileTmpName=$files['tmp_name'][$i];$fileName=$files['name'][$i];$fileType=$files['type'][$i];if(in_array($fileType,$allowedTypes)){$uploadStatus[]=['name'=>$fileName,'status'=>'success'];}else{$uploadStatus[]=['name'=>$fileName,'status'=>'error','message'=>'不支持些文件格式'];}}echo json_encode($uploadStatus);
}else
{echo json_encode(['message'=>'没有文件上传']);
}?>