UploadFiles.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. class UploadFiles extends Model
  5. {
  6. function upload($file,$path,$type=1,$size=2000)
  7. {
  8. if ($file->isValid()) {
  9. $filename = $file->getClientOriginalName();//获取上传文件的文件名(带后缀,如abc.png)
  10. $fileextension = $file->getClientOriginalExtension();//获取上传文件的后缀(如abc.png,获取到的为png)
  11. if($type==1){ // 图片
  12. $preg_str='/(jpg|jpeg|png|gif)/';
  13. }elseif($type==2){ // excel表格
  14. $preg_str='/(xlsx|xls|csv)/';
  15. }
  16. if (!preg_match($preg_str, strtolower($filename))) {
  17. return response()->json([
  18. 'msg' => '文件格式有误'
  19. ]);
  20. }
  21. $filesize = $file->getSize();//获取上传文件的大小
  22. if (($filesize / 1024) > $size) {
  23. return response()->json([
  24. 'msg' => '请检查您上传的文件不能大于'.$size.'KB'
  25. ]);
  26. }
  27. $newfilename = date("YmdHis") . mt_rand(1000, 9999) . substr(md5(uniqid(rand(1000, 9999))), 6, 18) . '.' . $fileextension;
  28. $newpath = $request->server('DOCUMENT_ROOT') . $path; // '/images/commit'
  29. $result = $file->move($newpath, $newfilename);
  30. if($result){
  31. return response()->json([
  32. 'filename'=>$newfilename,
  33. 'msg' => '文件上传成功'
  34. ]);
  35. }
  36. } else {
  37. return response()->json([
  38. 'msg' => '文件上传失败'
  39. ]);
  40. }
  41. }
  42. }