OssService.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: ywl
  5. * Date: 2018/4/12
  6. * Time: 下午11:18
  7. */
  8. namespace App\Common\Services;
  9. use App\Exceptions\ApiException;
  10. use App\Services\CommonBaseService;
  11. use OSS\Core\OssException;
  12. use OSS\OssClient;
  13. class OssService extends CommonBaseService
  14. {
  15. /**
  16. * 上传到云存储
  17. * @param $filePath
  18. * @param $fileName
  19. * @param $etag
  20. * @param string $type
  21. * @return string
  22. * @throws ApiException
  23. */
  24. public function uploadToOss($filePath, $fileName, &$etag, $type = 'share_center',$isReName=false)
  25. {
  26. if ($etag) {
  27. $oss = $this->model->where([
  28. 'etag' => strtoupper($etag)
  29. ])->first();
  30. if ($oss) {
  31. @unlink($filePath);
  32. return $oss['url'];
  33. }
  34. }
  35. $bucket = config('oss.bucketName');
  36. $ext = pathinfo($fileName, PATHINFO_EXTENSION);
  37. $oss = new OssClient(
  38. config('oss.accessKeyId'),
  39. config('oss.accessKeySecret'),
  40. config('oss.ossServerInternal')
  41. );
  42. $disposition = 'attachment;filename=' . $fileName;
  43. if (in_array(strtolower($ext), ['jpg', 'jpeg', 'gif', 'png'])) {
  44. $disposition = "";
  45. }
  46. $options = [
  47. OssClient::OSS_HEADERS => [
  48. 'Cache-Control' => 'max-age=365',
  49. 'Content-Disposition' => $disposition,
  50. // 'Content-Encoding' => 'utf-8',
  51. // 'Content-Language' => 'zh-CN',
  52. 'x-oss-server-side-encryption' => 'AES256',
  53. ],
  54. ];
  55. if($isReName){
  56. $object = config('oss.ossObject') .
  57. "/$type/" . date('Y') . "/" . date('md') . "/" . uniqid() . ($ext ? "." . $ext : "");
  58. }else{
  59. $object = config('oss.ossObject') .
  60. "/$type/" . date('Y') . "/" . date('md') . "/" .mt_rand(1000, 9999)."/". uniqid() . ($ext ? "/" . $fileName : "");
  61. }
  62. try {
  63. // print_r([$bucket, $object, $filePath, $options]);die;
  64. $response = $oss->uploadFile($bucket, $object, $filePath, $options);
  65. $url = $response['info']['url']??'';
  66. $url = str_replace(
  67. config('oss.ossServerInternalHttp').$bucket
  68. . "." . config('oss.ossServerInternal'),
  69. config("oss.ossServerHttp") . config('oss.ossServer'),
  70. $url
  71. );
  72. $this->save([
  73. 'etag' => trim($response['etag'], '"')??'',
  74. 'url' => $url,
  75. 'file_size' => filesize($filePath),
  76. ]);
  77. @unlink($filePath);
  78. return $url;
  79. } catch (OssException $e) {
  80. throw new ApiException(40008, [
  81. 'message' => $e->getMessage(),
  82. 'code' => $e->getCode()
  83. ]);
  84. }
  85. }
  86. }