UploadController.php 3.1 KB

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