You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.7 KiB
77 lines
2.7 KiB
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Helpers\ResponseCode;
|
|
use App\Models\Upload;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Validator;
|
|
|
|
class UploadController extends CommonController
|
|
{
|
|
|
|
/**
|
|
* @OA\Post(
|
|
* path="/api/admin/upload-file",
|
|
* tags={"其他"},
|
|
* summary="上传文件",
|
|
* description="",
|
|
* @OA\Parameter(name="file", in="query", @OA\Schema(type="file"), required=true, description="文件"),
|
|
* @OA\Parameter(name="token", in="query", @OA\Schema(type="string"), required=true, description="token"),
|
|
* @OA\Response(
|
|
* response="200",
|
|
* description="暂无"
|
|
* )
|
|
* )
|
|
*/
|
|
public function uploadFile(Request $request)
|
|
{
|
|
$all = \request()->all();
|
|
$messages = [
|
|
'file.required' => 'file必填',
|
|
'file.file' => 'file必须是文件',
|
|
'file.max' => '文件大小不能超过50MB',
|
|
'file.mimes' => '仅允许上传以下格式的文件: zip, rar, ppt, pptx, xls, xlsx, doc, docx, png, gif, jpg, jpeg, pdf, mp4, mp3'
|
|
];
|
|
$validator = Validator::make($all, [
|
|
'file' => 'required|file|mimes:zip,rar,ppt,pptx,xls,xlsx,doc,docx,png,gif,jpg,jpeg,pdf,mp4,mp3|max:51200000',
|
|
], $messages);
|
|
if ($validator->fails()) {
|
|
return $this->fail([ResponseCode::ERROR_PARAMETER, implode(',', $validator->errors()->all())]);
|
|
}
|
|
$file = $request->file('file');
|
|
//获取文件大小,单位B
|
|
$fileSize = floor($file->getSize());
|
|
//过滤文件后缀
|
|
$ext = $file->getClientOriginalExtension();
|
|
if ($ext == 'pdf') {
|
|
// 防止pdf的xss
|
|
$realPath = $file->getRealPath();
|
|
$content = strtolower(file_get_contents($realPath));
|
|
// 判断内容里有script字符串则返回错误,不区分大小写
|
|
if (stripos($content, 'javascript') !== false) {
|
|
return $this->fail([ResponseCode::ERROR_PARAMETER, '非法文件']);
|
|
}
|
|
}
|
|
// 保存目录
|
|
$dir = 'files';
|
|
// 文件名
|
|
$fileName = time() . uniqid() . '.' . $ext;
|
|
$file->storeAs($dir, $fileName, ['disk' => 'public']);
|
|
// 写入上传文件记录表
|
|
$list = [
|
|
'original_name' => $file->getClientOriginalName(),
|
|
'folder' => 'storage/' . $dir,
|
|
'name' => $fileName,
|
|
'extension' => $ext,
|
|
'size' => $fileSize,
|
|
'creator_id' => $this->getUserId(),
|
|
'created_at' => date('Y-m-d H:i:s')
|
|
];
|
|
$id = Upload::insertGetId($list);
|
|
$uploadFile = Upload::find($id);
|
|
return $this->success($uploadFile);
|
|
}
|
|
|
|
}
|