/**
* @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' => '添加失敗,請重試!']];
}