UploadController.php 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. $kuoname = $request->file('image')->getClientOriginalExtension();
  15. // //获取文件的类型
  16. // $type=$request->file('image')->getClientMimeType();
  17. // //获取文件的绝对路径,但是获取到的在本地不能打开
  18. $filePath = $request->file('image')->getRealPath();
  19. Log::debug('文件类型'.$kuoname);
  20. if (in_array($kuoname, ['jpg', 'jpeg', 'gif', 'png'])) {
  21. $width = Image::make($filePath)->width();
  22. $height = Image::make($filePath)->height();
  23. //要保存的文件名 时间+扩展名
  24. $filename = time() . '_' . uniqid() . '.' . $kuoname . '?' . $width . '_' . $height;
  25. } else {
  26. //要保存的文件名 时间+扩展名
  27. $filename = time() . '_' . uniqid() . '.' . $kuoname;
  28. }
  29. $imageUrl = Storage::put($path . $filename, file_get_contents($filePath));
  30. Log::debug('upload_url:' . $imageUrl);
  31. if ($imageUrl) {
  32. return $this->jsonSuccess(['url' => config('customer.chxq_oss_url') . $path . $filename]);
  33. } else {
  34. return $this->jsonError('图片上传失败,请重试');
  35. }
  36. } else {
  37. return $this->jsonError('仅支持图片上传,请重试');
  38. }
  39. }
  40. public function uploadImages(Request $request)
  41. {
  42. $files = $request->file('image');
  43. $fileCount = count($files);
  44. $urls = [];
  45. $path = $request->get('path') ? $request->get('path') . '/' : date('Ym') . '/';
  46. for ($i = 0; $i < $fileCount; $i++) {
  47. $kuoname = $files[$i]->getClientOriginalExtension();
  48. $filePath = $files[$i]->getRealPath();
  49. Log::debug('文件类型'.$kuoname);
  50. //要保存的文件名 时间+扩展名
  51. if (in_array($kuoname, ['jpg', 'jpeg', 'gif', 'png'])) {
  52. $width = Image::make($filePath)->width();
  53. $height = Image::make($filePath)->height();
  54. //要保存的文件名 时间+扩展名
  55. $filename = time() . '_' . uniqid() . '.' . $kuoname . '?' . $width . '_' . $height;
  56. } else {
  57. //要保存的文件名 时间+扩展名
  58. $filename = time() . '_' . uniqid() . '.' . $kuoname;
  59. }
  60. $imageUrl = Storage::put($path . $filename, file_get_contents($filePath));
  61. if ($imageUrl) {
  62. array_push($urls, config('customer.chxq_oss_url') . $path . $filename);
  63. } else {
  64. Log::debug('文件上传失败。' . $filename);
  65. }
  66. }
  67. if ($urls) {
  68. return $this->jsonSuccess($urls);
  69. } else {
  70. return $this->jsonError('图片上传失败,请重试');
  71. }
  72. }
  73. }