ImageController.php
17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
<?php
namespace App\Http\Controllers\File;
use App\Enums\Common\Code;
use App\Helper\Translate;
use App\Http\Controllers\Controller;
use App\Http\Controllers\type;
use App\Jobs\CopyProjectJob;
use App\Jobs\SyncImageFileJob;
use App\Models\File\ErrorFile;
use App\Models\File\Image as ImageModel;
use App\Models\Project\Project;
use App\Services\AmazonS3Service;
use App\Services\CosService;
use App\Services\TencentCosService;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Intervention\Image\Facades\Image;
class ImageController extends Controller
{
public $path = '';//路径
public $config = '';//存储默认配置
public $request = '';//request
public $param = '';//参数
public $token = '';//token
public $cache = '';//缓存数据
public $page = 1;
public $row = 20;
public $map = [];
public $upload_location = 0;//1:上传到cos
//上传图片类型
public $image_type = [
1 => 'image_product',
2 => 'image_news',
3 => 'image_blog',
4 => 'image_product_icon',
5 => 'image_product_cate',
0 => 'image_other',
];
public function __construct()
{
$this->request = request();
$this->param = $this->request->all();
$this->config = config('filesystems.disks.upload');
$this->uploads = config('upload.default_image');
$this->get_param();
//获取当前登录用户详情
$this->token = $this->request->header('token');
$this->cache = Cache::get($this->token);
}
/**
* @remark :参数过滤
* @name :get_param
* @author :lyh
* @method :post
* @time :2023/8/14 14:27
*/
public function get_param(){
$param = $this->param;
if(!empty($param)){
foreach ($param as $k => $v){
if(is_array($v)){
continue;
}
switch ($k){
case "order":
$this->order = $v;
break;
case 'page':
$this->page = $v;
break;
case 'row':
$this->row = $v;
break;
case "status":
$this->map['status'] = $v;
break;
default:
$this->map[$k] = $v;
break;
}
}
}
}
/**
* @name :index
* @author :lyh
* @method :post
* @time :2023/5/11 17:19
*/
public function index($hash = '', $w = 0 ,$h = 0 ){
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
header("HTTP/1.1 304 Not Modified");
exit;
}
$imageModel = new ImageModel();
$info = $imageModel->read(['hash'=>$hash]);
if ($info === false) {
$this->response('指定图片不存在!', Code::USER_ERROR);
}
if($info['is_cos'] == 1){
$filename = getImageUrl($info['path']);
$content = file_get_contents($filename);
$header['Content-Length'] = strlen($content);
}else{
//查看缩略图是否存在
$filename = $this->config['root'] . $info['path'] . '_' . $w . '_' . $h;
if(is_file($filename)){
$content = file_get_contents($filename);
$header['Content-Length'] = strlen($content);
}else{
$content = $this->readImageContent($info,$w,$h);
$header['Content-Length'] = strlen($content);
}
}
$header['Content-Type'] = $info['mime'];
return response($content,200,$header);
}
/**
* @remark :缩略图不存在时获取图片
* @name :readImageContent
* @author :lyh
* @method :post
* @time :2023/7/27 9:26
*/
public function readImageContent($info,$w,$h)
{
if ($w > 0 && $h > 0) {
$path = $this->cacheImage($info, $w, $h);
$content = file_get_contents($path);
} else {
$content = file_get_contents($this->config['root'] . $info['path']);
}
return $content;
}
/**
* @name :(图片上传)upload
* @author :lyh
* @method :post
* @time :2023/6/17 16:28
*/
public function upload() {
$this->request->validate([
'image'=>['required'],
],[
'image.required'=>'图片必须填写',
]);
$files = $this->request->file('image');
if (empty($files)) {
$this->response('没有上传的文件!', Code::USER_ERROR);
}
$type = $this->request->post('type','single');
$this->setUrl($files);
if ($type == 'multi') {
return $this->multi($files);
}else{
return $this->single($files);
}
}
/**
* @param $files
* @remark :单图片上传
* @name :single
* @author :lyh
* @method :post
* @time :2023/6/17 16:30
*/
public function single(&$files){
$hash = hash_file('sha256', $files->getPathname());
$name = $files->getClientOriginalName();
//查看文件是否存在
$imageModel = new ImageModel();
//查看图片是否已上传
$param = ['hash'=>$hash,'refer'=>$this->param['refer'] ?? 0,'is_cos'=>(($this->upload_location == 0) ? 1 : 0)];
if(isset($this->cache['project_id']) && !empty($this->cache['project_id'])){
$param['project_id'] = $this->cache['project_id'];
}
$image_hash = $imageModel->read($param);
if($image_hash !== false){
return $this->response('图片资源',Code::SUCCESS,$this->responseData($image_hash['path'], $name));
}
$image_type = $files->getClientOriginalExtension();
if(strlen($image_type) > 7){
$this->response('不支持当前格式',Code::SYSTEM_ERROR);
}
$fileName = $this->getOnlyFilename($name,$param['project_id'] ?? 0);
//上传到cos
if($this->upload_location == 0){
$cosService = new CosService();
$cosService->uploadFile($files,$this->path,$fileName);
}else{
//TODO::上传亚马逊
$amazonS3Service = new AmazonS3Service();
$amazonS3Service->uploadFiles($files,$this->path,$fileName);
}
$this->saveMysql($imageModel,$files->getSize(),$image_type,$fileName,$hash,$this->upload_location,$files->getMimeType(), $name);
$this->synchronizationImage($fileName,$this->upload_location);
return $this->response('图片资源',Code::SUCCESS,$this->responseData($this->path.'/'.$fileName, $name));
}
/**
* @remark :获取唯一名称
* @name :getOnlyFilename
* @author :lyh
* @method :post
* @time :2024/4/26 16:10
*/
public function getOnlyFilename($name,$project_id = 0){
$nameArr = explode('.',$name);
$suffix = array_pop($nameArr) ?? 'jpg';
$nameStr = implode('-', $nameArr);
$enName = generateRoute(Translate::tran($nameStr, 'en'));
$fileName = $enName;
$i=1;
while($this->onlyName($enName.'.'.$suffix,$project_id)){
$enName = $fileName .'-'.$i;
$i++;
}
return $enName.'.'.$suffix;
}
/**
* @remark :唯一名称
* @name :onlyName
* @author :lyh
* @method :post
* @time :2024/4/26 16:21
*/
public function onlyName($enName,$project_id){
$imageModel = new ImageModel();
$info = $imageModel->read(['project_id' => $project_id, 'en_name' => $enName]);
if($info !== false){
return true;
}
return false;
}
/**
* @remark :指定同步文件到獨立177服務器
* @name :synchronizationFile
* @author :lyh
* @method :post
* @time :2024/4/8 11:10
*/
public function synchronizationImage($fileName,$location){
SyncImageFileJob::dispatch(['path'=>$this->path,'name'=>$fileName,'location'=>$location]);
return true;
}
/**
* @remark :保存数据库
* @name :saveMysql
* @author :lyh
* @method :post
* @time :2023/7/19 16:38
*/
public function saveMysql(&$imageModel,$size,$image_type,$fileName,$hash,$is_cos = 0,$mime = '', $name=''){
$data = [
'path' => $this->path.'/'.$fileName,
'created_at' => date('Y-m-d H:i:s',time()),
'size' => $size,
'hash' => $hash,
'type'=>$image_type,
'refer'=>$this->param['refer'] ?? 0,
'is_cos'=>($is_cos == 0) ? 1 : 0,
'mime'=>$mime,
'project_id'=>$this->cache['project_id'] ?? 0,
'name'=>$name,
'en_name'=>$fileName
];
$rs = $imageModel->add($data);
if ($rs === false) {
return $this->response('添加失败', Code::USER_ERROR);
}
return true;
}
/**
* @remark :生成缩略图
* @name :cacheImage
* @author :lyh
* @method :post
* @time :2023/6/17 16:31
*/
private function cacheImage($info, $w, $h) {
$path = $info['path'];
$filename = $this->config['root'] . '/' . $info['path'] . '_' . $w . '_' . $h;
Image::make($path)->resize($w, $h)->save($filename);
return $filename;
}
/**
* @remark :多图片上传
* @name :multi
* @author :lyh
* @method :post
* @time :2023/6/17 16:31
*/
private function multi(&$files) {
$data = [];
foreach ($files as $file) {
try {
$hash = hash_file('sha256', $file->getPathname());
$imageModel = new ImageModel();
//查看图片是否已上传
$param = ['hash'=>$hash,'refer'=>$this->param['refer'] ?? 0,'is_cos'=>(($this->upload_location == 0) ? 1 : 0)];
if(isset($this->cache['project_id']) && !empty($this->cache['project_id'])){
$param['project_id'] = $this->cache['project_id'];
}
$image_hash = $imageModel->read($param);
if($image_hash !== false){
$data[] = $this->responseData($image_hash['path'],$image_hash['name']);
continue;
}
$name = $file->getClientOriginalName();
$fileName = $this->getOnlyFilename($name,$param['project_id'] ?? 0);
$image_type = $file->getClientOriginalExtension();
$this->saveMysql($imageModel,$file->getSize(),$image_type,$fileName,$hash,$this->upload_location,$file->getMimeType(),$name);
//同步数据到cos
if($this->upload_location == 0){
$cosService = new CosService();
$cosService->uploadFile($file,$this->path,$fileName);
}else{
//TODO::上传亚马逊
$amazonS3Service = new AmazonS3Service();
$amazonS3Service->uploadFiles($file,$this->path,$fileName);
}
$this->synchronizationImage($fileName,$this->upload_location);
$data[] = $this->responseData($this->path.'/'.$fileName,$name);
}catch (\Exception $e){
$this->response('图片资源',Code::SUCCESS,$data);
}
}
$this->response('图片资源',Code::SUCCESS,$data);
}
/**
* @param $filename
* @remark :下载
* @name :download
* @author :lyh
* @method :post
* @time :2023/7/19 17:59
*/
public function download(){
$imageModel = new ImageModel();
$info = $imageModel->read(['path' => str_replace_url($this->param['path'])]);
if ($info === false) {
$this->response('指定文件不存在!', Code::USER_ERROR);
}
if($info['is_cos'] == 1){
$cos = new CosService();
$fileUrl = $cos->getImageUrl($info['path']);
}else{
$fileUrl = $this->config['root'].$info['path'];
if (!is_file($fileUrl)) {
$this->response('指定图片已被系统删除!', Code::USER_ERROR);
}
}
// $fileName = basename($info['path']); // 要保存的文件名
// 设置响应头
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $info['name'] . '"');
// 下载文件
readfile($fileUrl);
}
/**
* @remark :统一返回
* @name :response
* @author :lyh
* @method :post
* @time :2023/7/19 17:59
*/
public function response($msg = null,string $code = Code::SUCCESS,$data = [],$result_code = 200,$type = 'application/json'): JsonResponse
{
$code = Code::fromValue($code);
$result = [
'message' => $msg == ' ' ? $code->description : $msg,
'code' => $code->value,
'data' => $data,
];
$this->header['Content-Type'] = $type;
$response = response($result,$result_code,$this->header);
throw new HttpResponseException($response);
}
/**
* @remark :获取所有图片
* @name :getImageList
* @author :lyh
* @method :post
* @time :2023/6/29 11:48
*/
public function getImageList(){
if(isset($this->cache['project_id']) && !empty($this->cache['project_id'])){
$this->map['project_id'] = $this->cache['project_id'];
}
if(isset($this->map['name']) && !empty($this->map['name'])){
$this->map['name'] = ['like','%'.$this->map['name'].'%'];
}
$imageModel = new ImageModel();
$lists = $imageModel->lists($this->map,$this->page,$this->row);
if(!empty($lists) && !empty($lists['list'])){
foreach ($lists['list'] as $k => $v){
$v['image_link'] = getImageUrl($v['path'],$this->cache['storage_type'] ?? 0,$this->cache['project_location']);
$lists['list'][$k] = $v;
}
}
$this->response('success',Code::SUCCESS,$lists);
}
/**
* @remark :保存路径
* @name :setUrl
* @author :lyh
* @method :post
* @time :2023/7/18 15:36
*/
public function setUrl($files){
//A端上传
if(isset($this->param['refer_type']) && $this->param['refer_type'] == 1){
$this->path = $this->uploads['path_a'].'/'.$this->image_type[$this->param['refer']].'/'.date('Y-m');
}else{
//TODO::设置上传文件大小(B端上传)
$max = config('upload.default_b_image')['size']['max'];
if(is_array($files)){
foreach ($files as $file){
if(isset($this->cache['image_max']) && ($this->cache['image_max'] != 0)){
if ($file->getSize() > $this->cache['image_max'] * 1024) {
$this->response('图片最大为'.$this->cache['image_max'],Code::SYSTEM_ERROR);
}
}else{
if ($file->getSize() > $max) {
$this->response('图片最大为1024K',Code::SYSTEM_ERROR);
}
}
}
}else{
if(isset($this->cache['image_max']) && ($this->cache['image_max'] != 0)){
if ($files->getSize() > $this->cache['image_max'] * 1024) {
$this->response('图片最大为'.$this->cache['image_max'],Code::SYSTEM_ERROR);
}
}else{
if ($files->getSize() > $max) {
$this->response('图片最大为1024K',Code::SYSTEM_ERROR);
}
}
}
if(!isset($this->param['upload_method'])){
//根据项目上传标识区分上传到cos/本地
$projectModel = new Project();
$project_info = $projectModel->read(['id'=>$this->cache['project_id']],['project_location']);
if ($project_info['project_location'] != 0) {
//TODO::危险项目时
$this->upload_location = 1;//上传到cos
}
}
$this->path = $this->uploads['path_b'].'/'.$this->cache['project_id'].'/'.$this->image_type[$this->param['refer']].'/'.date('Y-m');
}
}
/**
* @remark :统一返回参数处理
* @name :responseData
* @author :lyh
* @method :post
* @time :2023/7/26 13:41
*/
public function responseData($path = '', $name = ''){
$data = [
'image'=>$path,
'image_link'=>getImageUrl($path,$this->cache['storage_type'] ?? 0,$this->cache['project_location'] ?? 0),
'name'=>$name,
'image_download'=>url('a/download_images?path='.$path)
];
return $data;
}
/**
* @remark :获取下载链接
* @name :getDownloadUrl
* @author :lyh
* @method :post
* @time :2023/7/26 14:00
*/
public function getDownloadUrl(){
$imageModel = new ImageModel();
$info = $imageModel->read(['path' => str_replace_url($this->param['path'])]);
if ($info === false) {
$this->response('指定文件不存在!', Code::USER_ERROR);
}
$data = ['image_download'=>url('a/download_images?path='.$info['path']), 'name' => $info['name']];
$this->response('success',Code::SUCCESS,$data);
}
}