fastadmin文件API接口文件下的common修改默认的upload方法,直接替换即可
/*** 上传文件* @ApiMethod (POST)* @param File $file 文件流*/public function upload(){$file = $this->request->file('file');if (empty($file)) {$this->error(__('No file upload or server upload limit exceeded'));}//判断是否已经存在附件$sha1 = $file->hash();$upload = Config::get('upload');preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);$type = strtolower($matches[2]);$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];$size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);$fileInfo = $file->getInfo();$suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));$suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';$mimetypeArr = explode(',', strtolower($upload['mimetype']));$typeArr = explode('/', $fileInfo['type']);//禁止上传PHP和HTML文件if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {$this->error(__('Uploaded file format is limited'));}//验证文件后缀if ($upload['mimetype'] !== '*' &&(!in_array($suffix, $mimetypeArr)|| (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr))))) {$this->error(__('Uploaded file format is limited'));}//验证是否为图片文件$imagewidth = $imageheight = 0;if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {$imgInfo = getimagesize($fileInfo['tmp_name']);if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {$this->error(__('Uploaded file is not a valid image'));}$imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;$imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;}$replaceArr = ['{year}' => date("Y"),'{mon}' => date("m"),'{day}' => date("d"),'{hour}' => date("H"),'{min}' => date("i"),'{sec}' => date("s"),'{random}' => Random::alnum(16),'{random32}' => Random::alnum(32),'{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],'{suffix}' => $suffix,'{.suffix}' => $suffix ? '.' . $suffix : '','{filemd5}' => md5_file($fileInfo['tmp_name']),];$savekey = $upload['savekey'];$savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);$uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);$fileName = substr($savekey, strripos($savekey, '/') + 1);//$splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);if ($splInfo) {$params = array('admin_id' => 0,'user_id' => (int)$this->auth->id,'filesize' => $fileInfo['size'],'imagewidth' => $imagewidth,'imageheight' => $imageheight,'imagetype' => $suffix,'imageframes' => 0,'mimetype' => $fileInfo['type'],'url' => $uploadDir . $splInfo->getSaveName(),'uploadtime' => time(),'storage' => 'local','sha1' => $sha1,);$attachment = new Attachment();$attachment->data(array_filter($params));$attachment->save();// 文件上传至七牛云$config = get_addon_config('qiniu');$filePath = $splInfo->getRealPath() ?: $splInfo->getPathname();$policy = array('saveKey' => ltrim($savekey, '/'),);$auth = new \Qiniu\Auth($config['accessKey'], $config['secretKey']);$token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);$multipart = [['name' => 'token', 'contents' => $token],['name' => 'file','contents' => fopen($filePath, 'r'),'filename' => $fileName,]];try {$client = new \GuzzleHttp\Client();$res = $client->request('POST', $config['uploadurl'], ['multipart' => $multipart]);$code = $res->getStatusCode();//成功不做任何操作} catch (\GuzzleHttp\Exception\ClientException $e) {$attachment->delete();unlink($filePath);$this->error("上传失败");}//上传成功后将存储变更为qiniu$attachment->storage = 'qiniu';$attachment->save();\think\Hook::listen("upload_after", $attachment);$this->success(__('Upload successful'), ['url' => $uploadDir . $splInfo->getSaveName(),'fullurl' => cdnurl($uploadDir . $splInfo->getSaveName(), true)]);} else {// 上传失败获取错误信息$this->error($file->getError());Config::set('default_return_type', 'json');//必须设定cdnurl为空,否则cdnurl函数计算错误Config::set('upload.cdnurl', '');$chunkid = $this->request->post("chunkid");if ($chunkid) {if (!Config::get('upload.chunking')) {$this->error(__('Chunk file disabled'));}$action = $this->request->post("action");$chunkindex = $this->request->post("chunkindex/d");$chunkcount = $this->request->post("chunkcount/d");$filename = $this->request->post("filename");$method = $this->request->method(true);if ($action == 'merge') {$attachment = null;//合并分片文件try {$upload = new Upload();$attachment = $upload->merge($chunkid, $chunkcount, $filename);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);} elseif ($method == 'clean') {//删除冗余的分片文件try {$upload = new Upload();$upload->clean($chunkid);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success();} else {//上传分片文件//默认普通上传文件$file = $this->request->file('file');try {$upload = new Upload($file);$upload->chunk($chunkid, $chunkindex, $chunkcount);} catch (UploadException $e) {$this->error($e->getMessage());}$this->success();}} else {$attachment = null;//默认普通上传文件$file = $this->request->file('file');try {$upload = new Upload($file);$attachment = $upload->upload();} catch (UploadException $e) {$this->error($e->getMessage());}$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);}}}
注意:
后台七牛云插件中需要修改的地方