UploadController.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Storage;
  6. use Intervention\Image\Facades\Image;
  7. class UploadController extends Controller
  8. {
  9. public function uploadImage(Request $request)
  10. {
  11. if ($request->hasFile('image') && $request->file('image')->isValid()) {
  12. $path = $request->get('path') ? $request->get('path') . '/' : date('Ym') . '/';
  13. //获取文件的原文件名 包括扩展名
  14. // $yuanname= $request->file('image')->getClientOriginalName();
  15. // //获取文件的扩展名
  16. $kuoname = $request->file('image')->getClientOriginalExtension();
  17. // //获取文件的类型
  18. // $type=$request->file('image')->getClientMimeType();
  19. // //获取文件的绝对路径,但是获取到的在本地不能打开
  20. $filePath = $request->file('image')->getRealPath();
  21. //要保存的文件名 时间+扩展名
  22. if (in_array($kuoname, ['jpg', 'jpeg', 'png'])) {
  23. $width = Image::make($filePath)->width();
  24. $height = Image::make($filePath)->height();
  25. //要保存的文件名 时间+扩展名
  26. $filename = time() . '_' . uniqid() . '*' . $width . '_' . $height . '.' . $kuoname;
  27. } else {
  28. //要保存的文件名 时间+扩展名
  29. $filename = time() . '_' . uniqid() . '.' . $kuoname;
  30. }
  31. $imageUrl = Storage::put($path . $filename, file_get_contents($filePath));
  32. if ($imageUrl) {
  33. return [
  34. 'data' => ['url' => $path . $filename]
  35. ];
  36. } else {
  37. return $this->response->error('图片上传失败,请重试', 500);
  38. }
  39. } else {
  40. return $this->response->error('图片上传失败,请重试', 500);
  41. }
  42. }
  43. public function uploadImages(Request $request)
  44. {
  45. $files = $request->file('image');
  46. $fileCount = count($files);
  47. $urls = [];
  48. for ($i = 0; $i < $fileCount; $i++) {
  49. $kuoname = $files[$i]->getClientOriginalExtension();
  50. $filePath = $files[$i]->getRealPath();
  51. //要保存的文件名 时间+扩展名
  52. if (in_array($kuoname, ['jpg', 'jpeg', 'png'])) {
  53. $width = Image::make($filePath)->width();
  54. $height = Image::make($filePath)->height();
  55. //要保存的文件名 时间+扩展名
  56. $filename = time() . '_' . uniqid() . '*' . $width . '_' . $height . '.' . $kuoname;
  57. //todo 等待客户端更新后替换为下列规则
  58. //$filename = time() . '_' . uniqid() . '.' . $kuoname . '?' . $width . '_' . $height;
  59. } else {
  60. //要保存的文件名 时间+扩展名
  61. $filename = time() . '_' . uniqid() . '.' . $kuoname;
  62. }
  63. $imageUrl = Storage::put($filename, file_get_contents($filePath));
  64. if ($imageUrl) {
  65. array_push($urls, $filename);
  66. } else {
  67. Log::debug('文件上传失败。' . $filename);
  68. }
  69. }
  70. if ($urls) {
  71. return [
  72. 'data' => $urls
  73. ];
  74. } else {
  75. return $this->response->error('图片上传失败,请重试', 500);
  76. }
  77. }
  78. }