lumen 支持多文件上传

时间:2023-03-10 03:17:43
lumen 支持多文件上传

1、webform (注意:name后面一定要加[]号)

<form method="post" enctype="multipart/form-data" action="http://127.0.0.1/mobile/public/api/wx/user/upload" >
First name: <input type="file" name="file[]" /><br />
First name: <input type="file" name="file[]" /><br />
Last name: <input type="text" name="token" /><br />
<input type="submit" value="提交" />
</form>

  注:HTML5的文件已经支持多文件上传:

<input type="file" name="file[]"  multiple/>

2、后端处理

 /*上传文件到服务器*/
public function uploadFile(\Illuminate\Http\Request $request)
{ $this->validate($request,array('token'=>'required|string'));
$this->validationUser($uid,$this->authService);
if($request->hasFile('file')) {
$root = $request->server('DOCUMENT_ROOT');
$file = $request->file('file');
//return var_dump($file);
$filePath=[]; // 定义空数组用来存放图片路径
foreach ($file as $k => $v) {
// 判断图片上传中是否出错
if (!$v->isValid()) {
$this->apiReturn("上传图片出错,请重试!",1);
}
//此处防止没有多文件上传的情况
if(!empty($v)){
if ($v->getSize() / 1024 > 600)
return $this->apiReturn("请检查您上传的文件不能大于600KB", 1);
$fileName = strtolower($v->getClientOriginalName());
if (!preg_match('/\.(jpg|jpeg|png|gif)$/', $fileName))
return $this->apiReturn("您只能上传通用的图片格式", 1);
$destinationPath = '/mobile/resources/uploads/' . date('Ymd');
$fileExtendName = substr($fileName, strpos($fileName, '.'));
$realPath = $root . $destinationPath;
if (!file_exists($realPath))
mkdir($realPath);
$newFileName = uniqid() . mt_rand(1, 100000) . $fileExtendName;
$v->move($realPath, $newFileName);
$filePath[]=$destinationPath . '/' . $newFileName;
}}
return $this->apiReturn(json_encode($filePath), 0);
}
else
return $this->apiReturn('请选择文件再上传', 1);
}

原生多文件上传:

/*多文件上传*/
public function uploadImg($file_name,$dir,$format='string')
{
$file = $_FILES[$file_name];
if($file) {
$root =$_SERVER['DOCUMENT_ROOT'];
$filePath=[]; // 定义空数组用来存放图片路径
$fileNumber=count($file['name']);
for($i=0;$i<$fileNumber;$i++) { //此处防止没有多文件上传的情况
if(!empty($file['name'][$i])){
if ($file['size'][$i] / 1024 > 600)
{
return ['error'=>"请检查您上传的文件不能大于600KB"];
} $fileName = strtolower($file['name'][$i]);
if (!preg_match('/\.(jpg|jpeg|png|gif)$/', $fileName))
{
return ['error'=>'您只能上传通用的图片格式'];
} $destinationPath = $dir. date('Ymd');
$fileExtendName = substr($fileName, strpos($fileName, '.'));
$realPath = $root . $destinationPath;
if (!file_exists($realPath))
{
make_dir($realPath);
}
$newFileName = uniqid() . mt_rand(1, 100000) . $fileExtendName;
move_uploaded_file($file['tmp_name'][$i], $realPath.'/'.$newFileName);
$filePath[]=$destinationPath . '/' . $newFileName; }
}
if($format=='string')
return implode(',',$filePath);
}
else
return ['error'=>'请选择文件再上传'];
}