FileServer.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Servers;
  3. // 文件上传
  4. use Illuminate\Http\Request;
  5. class FileServer
  6. {
  7. /**
  8. * @param Request $request
  9. * @param string $file
  10. * @param string $path
  11. * @param int $size
  12. * @return array
  13. *
  14. * 上传单张图片
  15. */
  16. static public function imageOne(Request $request, $file = 'file', $path = 'image', $size = 5)
  17. {
  18. if( $request->isMethod('post') ){
  19. $returnDatum = array('errcode'=>1,'errmsg'=>'','url'=>'');
  20. if( $request->hasFile($file) ){
  21. $ext = $request->file($file)->extension(); // 文件后缀判断
  22. if( !in_array($ext,["jpg", "jpeg", "gif", "png", "bmp", "webp"]) ){
  23. $returnDatum['errmsg'] = config('lang', 'zh') === 'zh' ? '上传图片仅支持png、jpg、jpeg、gif、bmp、webp后缀!!!' : 'stand by png、jpg、jpeg、gif、bmp、webp';
  24. return $returnDatum;
  25. }
  26. // 文件大小是否满足 5M = 5*1024*1024 B
  27. if( $request->file($file)->getClientSize() > $size * 1048576 ){
  28. $returnDatum['errmsg'] = config('lang', 'zh') === 'zh' ? '上传图片大小超过5M!!!' : 'Upload image size exceeds 5M.';
  29. return $returnDatum;
  30. }
  31. // 上传过程是否出错
  32. if( ! $request->file($file)->isValid() ){
  33. $returnDatum['errmsg'] = config('lang', 'zh') === 'zh' ? '上传文件出错,请重试!!!' : 'Error uploading file, please try again.';
  34. return $returnDatum;
  35. }
  36. // 文件保存 生成一个唯一的文件名称
  37. $fileName = time().str_random(4).mt_rand(1000,9999).".{$ext}";
  38. $pathUrl = $request->file($file)->storeAs($path.'/'.date('y-m',time()),$fileName,'public');
  39. if( $pathUrl ){
  40. $returnDatum['errcode'] = 0;
  41. $returnDatum['url'] = asset('storage').DIRECTORY_SEPARATOR.$pathUrl;
  42. return $returnDatum;
  43. }else{
  44. $returnDatum['errmsg'] = config('lang', 'zh') === 'zh' ? '图片上传保存失败,请重试!!!' : 'Image upload failed to save, please try again.';
  45. return $returnDatum;
  46. }
  47. }else{
  48. $returnDatum['errmsg'] = config('lang', 'zh') === 'zh' ? '请上传图片文件!!!' : 'Please upload an image file.';
  49. return $returnDatum;
  50. }
  51. }else{
  52. return array('errcode'=>1,'errmsg'=>'无效请求!','url'=>'');
  53. }
  54. }
  55. }