123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- <?php
- namespace App\Models;
- use Illuminate\Database\Eloquent\Model;
- class UploadFiles extends Model
- {
- function upload($file,$path,$type=1,$size=2000)
- {
- if ($file->isValid()) {
- $filename = $file->getClientOriginalName();//获取上传文件的文件名(带后缀,如abc.png)
- $fileextension = $file->getClientOriginalExtension();//获取上传文件的后缀(如abc.png,获取到的为png)
- if($type==1){ // 图片
- $preg_str='/(jpg|jpeg|png|gif)/';
- }elseif($type==2){ // excel表格
- $preg_str='/(xlsx|xls|csv)/';
- }
- if (!preg_match($preg_str, strtolower($filename))) {
- return response()->json([
- 'msg' => '文件格式有误'
- ]);
- }
- $filesize = $file->getSize();//获取上传文件的大小
- if (($filesize / 1024) > $size) {
- return response()->json([
- 'msg' => '请检查您上传的文件不能大于'.$size.'KB'
- ]);
- }
- $newfilename = date("YmdHis") . mt_rand(1000, 9999) . substr(md5(uniqid(rand(1000, 9999))), 6, 18) . '.' . $fileextension;
- $newpath = $request->server('DOCUMENT_ROOT') . $path; // '/images/commit'
- $result = $file->move($newpath, $newfilename);
- if($result){
- return response()->json([
- 'filename'=>$newfilename,
- 'msg' => '文件上传成功'
- ]);
- }
- } else {
- return response()->json([
- 'msg' => '文件上传失败'
- ]);
- }
- }
- }
|