批改状态:合格
老师批语:
form表单的enctype的默认值
如果表单中有文件或者图片之类的不能被编码的元素,浏览器可以用此方式传输数据,提高传输效果和用户体验,也可以减少服务器的请求次数.
此方法可以传输json数据, 跨脚本
html
<form action="upload.php" method="post" enctype="multipart/form-data"><input type="file" name="my_file"><button>提交</button></form>
php
print_r(uploadFile($_FILES));function uploadFile(array $files,$uploadPath='uploads'):array{if(!file_exists($uploadPath)){ //判断存储的路径是否存在,不存在即创建文件夹mkdir($uploadPath,0777,true); //默认权限是 0777最大可能的访问权}foreach($files as $file){if($file['error']==0){ //error==0表示无错误if(strstr($file['type'],'/',true)!=='image'){ //strstr 查找字符串中首次出现 true表示返回前面部分$tips = $file['name'].'文件类型错误';continue;}else{//生成文件名$targetName = $uploadPath.'/'.date('YmdHis').md5($file['name']).time().strstr($file['name'],'.');// echo $targetName;// die;//将文件从临时位置移动到指定位置if(!move_uploaded_file($file['tmp_name'],$targetName)){$tips = $file['name'].'文件移动失败';continue; //循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。}else{$img[] = $targetName;}}}}if(!empty($tips)){$res['error'] = $tips;}$res['fileRealPath'] = $img;return $res;}
html
<form action="uploads.php" method="post" enctype="multipart/form-data"><input type="file" name="my_file[]" multiple><button>多个文件上传</button></form>
php
$res = upload($_FILES);print_r(uploadFile($res));function uploadFile(array $files,$uploadPath='uploads/storage'):array{if(!file_exists($uploadPath)){ //判断存储的路径是否存在,不存在即创建文件夹mkdir($uploadPath,0777,true); //默认权限是 0777最大可能的访问权}foreach($files as $file){if($file['error']==0){ //error==0表示无错误if(strstr($file['type'],'/',true)!=='image'){ //strstr 查找字符串中首次出现 true表示返回前面部分$tips = $file['name'].'文件类型错误';continue;}else{//生成文件名$targetName = $uploadPath.'/'.date('YmdHis').md5($file['name']).time().strstr($file['name'],'.');// echo $targetName;// die;//将文件从临时位置移动到指定位置if(!move_uploaded_file($file['tmp_name'],$targetName)){$tips = $file['name'].'文件移动失败';continue; //循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。}else{$img[] = $targetName;}}}}if(!empty($tips)){$res['error'] = $tips;}$res['fileRealPath'] = $img;return $res;}// 处理多文件的格式function upload(): array{$i = 0;foreach ($_FILES as $k => $file) {// printf('<pre>%s</pre>', print_r($file, true));foreach ($file['name'] as $k => $v) {$files[$i]['name'] = $file['name'][$k];$files[$i]['type'] = $file['type'][$k];$files[$i]['tmp_name'] = $file['tmp_name'][$k];$files[$i]['error'] = $file['error'][$k];$files[$i]['size'] = $file['size'][$k];$i++;}}// printf('<pre>%s</pre>', print_r($files, true));return $files;}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号