php 上传文件 函数 收集

/**
* @param $file 长传文件的信息 $_FILES
* @param $allow 允许文件上传的类型
* @param $error 引用传递记录错误信息
* @param $path 文件上传目录
* @param int $maxsize 文件上传大小
* @return bool|false|string
*/
function uploadFile($file, $allow, &$error, $path, $maxsize =30720){
//先判断系统错误
switch ($file['error']) {
case 1:
$error = '上传错误,超出了服务器文件限制的大小!';
return false;
case 2:
$error = '上传错误,超出了浏览器表单允许的大小!';
return false;
case 3:
$error = '上传错误,文件上传不完整!';
return false;
case 4:
$error = '上传错误,请您先选择要上传的文件!';
return false;
case 6:
case 7:
$error = '对不起,服务器繁忙,请稍后再试!';
return false;
}
//判断逻辑错误
//验证文件的大小
if ($file['size'] > $maxsize) {
//超出用户了自己规定的大小
$error = '上传错误,超出了文件限制的大小!';
return false;
}
//判断文件的类型
if (!in_array($file['type'], $allow)) {
//非法的文件类型
$error = '上传的文件的类型不正确,允许的类型有:'.implode(',', $allow);
return false;
}
//移动临时文件
//指定文件上传后保存的路径
$newname = $this->randName($file['name']); //得到文件新的名字
//判断$path 目录是否存在 不存在则创建
$fileD = '/qhjjh' . date('Ymd', time()) . "/";
$filCate = $path . $fileD;
$realName = $fileD . $newname;
if (!file_exists($filCate)) {
mkdir($filCate, 0777, true);
}
$target = $filCate . '/' . $newname;
$result = move_uploaded_file($file['tmp_name'], $target);
if ($result) {
//上传成功
return $realName;
}else{
//上传失败
$error = '发生未知错误,上传失败';
return false;
}
}
1、上面是上传文件的函数
2、在项目中的应用,调用上面的上传文件函数
//对上传的文件进行保存
$file = $_FILES['article_file'];
//'image/jpeg', 'image/png', 'image/jpg', 'image/gif',
$allow = array(
'application/pdf',
'application/vnd.ms-excel',
'text/plain',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'application/vnd.openxmlformats-officedocument.presentationml.template',
'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml.slide',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/vnd.ms-excel.addin.macroEnabled.12',
'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
);
$path = public_path('uploads');
$maxsize = 1024 * 1024;
$result = $this->uploadFile($file,$allow,$error,$path,$maxsize);
if (!$result) {
//上传失败
return ['code' => 1002, 'data' => ['message' => $error]];
}
//上传文件成功就将文件计入数据库 /qhjjh20190606/20190606103856345056.pdf
$article['article_file'] = $result;
$res_id = \DB::table('article')->insertGetId($article);
if(!$res_id){
\DB::rollback();
\DB::commit();
return ['code' => 1003, 'data' => ['message' => '添加失败,请重试!']];
}