laravelͼƬÔõôÉèÖÃ
laravel ÊÇÒ»ÖÖÊ¢ÐÐµÄ php ¿ò¼Ü£¬ËüÄܹ»×ÊÖú¿ª·¢Õß¿ìËÙ¹¹½¨¡¢²âÊԺͰ²ÅÅ web Ó¦ÓóÌÐò¡£ÔÚÐí¶àÓ¦ÓóÌÐòÖУ¬Í¼ÏñºÍͼƬµÈ¶àýÌåÎļþÊDZز»¿ÉÉٵġ£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÏêϸÏÈÈÝ laravel ÖÐÔõÑùÉèÖÃͼƬ£¬ÒԱ㽫ͼÏñºÍͼƬÌí¼Óµ½ÄúµÄÓ¦ÓóÌÐòÖС£
×°ÖÃ Laravel
ÔÚ×îÏÈ֮ǰ£¬ÄúÐèÒªÔÚÍâµØÅÌËã»úÉÏ×°Öà Laravel¡£Äú¿ÉÒÔÇ°Íù Laravel µÄ¹Ù·½ÍøÕ¾£¨https://laravel.com/docs/8.x/installation£©Éó²é Laravel µÄ×°ÖÃÖ¸ÄÏ¡£
½¨Éè¿ØÖÆÆ÷
ÔÚ Laravel ÖУ¬¿ØÖÆÆ÷ÓÃÓÚ´¦ÀíÓû§ÇëÇó²¢·µ»ØÏìÓ¦¡£ÔÚ½¨Éè¿ØÖÆÆ÷֮ǰ£¬Ê×ÏÈÐèÒª½¨ÉèÒ»¸ö Laravel Ó¦ÓóÌÐò¡£ÔÚ½¨Éè Laravel Ó¦ÓóÌÐòºó£¬Ê¹ÓÃÒÔÏÂÏÂÁÉèÒ»¸öеÄͼƬ¿ØÖÆÆ÷£º
php artisan make:controller ImageController
µÇ¼ºó¸´ÖÆ
ÉèÖô洢
ÔÚ Laravel ÖУ¬Äú¿ÉÒÔʹÓÃÎļþϵͳ»òÔÆ´æ´¢À´ÉúÑÄͼÏñºÍͼƬ¡£Laravel ÌṩÁËÒ»¸ö¼òÆÓµÄͳһ API£¬Ê¹ÔÚÍâµØÎļþϵͳºÍÔÆ´æ´¢Ö®¼äÇл»ºÜÊÇÈÝÒס£
3.1 ´æ´¢ÔÚÍâµØÎļþϵͳ
Laravel Ö§³Ö½«Í¼ÏñºÍͼƬ´æ´¢ÔÚÍâµØÎļþϵͳÖС£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´ÔÚ Laravel Ó¦ÓóÌÐòÖÐÉèÖÃÍâµØÎļþϵͳ£º
php artisan storage:link
µÇ¼ºó¸´ÖÆ
±ðµÄ£¬ÄúÒ²¿ÉÒÔÔÚ config/filesystems.php ÎļþÖÐÉèÖÃÍâµØÎļþϵͳ£º
'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ],
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬storage_path(‘app’) ÊÇÓÃÓڴ洢ͼÏñºÍͼƬµÄ·¾¶¡£Äú¿ÉÒÔƾ֤×Ô¼ºµÄÐèÒªÐ޸ĴË·¾¶¡£
3.2 ´æ´¢ÔÚÔÆ´æ´¢
ÈôÊÇÄúµÄÓ¦ÓóÌÐòÐèÒª´¦Àí´ó×ÚͼÏñºÍͼƬ£¬²¢ÇÒÐèÒªÔÚ²î±ðµÄ×°±¸Ö®¼ä¹²ÏíËüÃÇ£¬ÔòÓ¦½«ËüÃÇ´æ´¢ÔÚÔÆ´æ´¢ÖУ¬Èç Amazon S3 »ò Google Cloud Storage¡£
ҪʹÓà Laravel ÖеÄÔÆ´æ´¢£¬ÄúÐèÒªÔÚ config/filesystems.php ÎļþÖÐÉèÖÃÔÆ´æ´¢£º
's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION'), 'bucket' => env('AWS_BUCKET'), ],
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬AWS_ACCESS_KEY_ID¡¢AWS_SECRET_ACCESS_KEY¡¢AWS_DEFAULT_REGION ºÍ AWS_BUCKET ÊǴ洢ͰµÄÈÏ֤ϸ½Ú¡£ÄúÐèÒªÏòÔÆ´æ´¢ÌṩÕâЩϸ½Ú£¬ÒÔ±ã Laravel ¿ÉÒÔ»á¼ûÄúµÄ´æ´¢Í°²¢½«Í¼ÏñºÍͼƬ´æ´¢ÔÚÆäÖС£
ÉÏ´«Í¼Æ¬
ÔÚ Laravel ÖУ¬Äú¿ÉÒÔʹÓà Laravel Îļþϵͳ£¨IlluminateFilesystemFilesystem£©ÀàÀ´ÉÏ´«Í¼ÏñºÍͼƬ¡£Òª×îÏÈÉÏ´«Îļþ£¬ÄúÐèÒªÔÚ¿ØÖÆÆ÷ÖбàдÒÔÏ´úÂ룺
public function upload(Request $request) { if ($request->hasFile('image')) { $file = $request->file('image'); $fileName = $file->getClientOriginalName(); $filePath = $file->storeAs('/public', $fileName); return $filePath; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬ÎÒÃǼì²éÁË HTTP ÇëÇóÖÐÊÇ·ñ±£´æÒ»¸öÃûΪ image µÄÎļþ¡£ÈôÊDZ£´æ£¬Ôò¿ÉÒÔʹÓà $file ¹¤¾ß»á¼û¸ÃÎļþ¡£ÎÒÃÇʹÓà $file->getClientOriginalName() »ñÈ¡ÎļþµÄÔʼÃû³Æ£¬²¢Ê¹Óà $file->storeAs() ÒªÁ콫Îļþ´æ´¢ÔÚÖ¸¶¨µÄ·¾¶ºÍÎļþÃûÏ¡£´ËʾÀýÖУ¬ÎÒÃǽ«Îļþ´æ´¢ÔÚ public Ŀ¼Ï¡£
ÏÔʾͼƬ
ÔÚ Laravel ÖУ¬Äú¿ÉÒÔʹÓà Blade Ä£°åÒýÇæÏÔʾͼÏñºÍͼƬ¡£ÀýÈ磬ÈôÊÇÄúÔÚÄ£°åÖÐÓÐÒÔÏ´úÂ룺
<img src="{{ asset('storage/image.jpg') }}" alt="Image">
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬ÎÒÃÇʹÓà asset() º¯ÊýÌìÉúͼÏñµÄ URL¡£¸Ãº¯Êý½«ÏòÖ¸¶¨Â·¾¶ÖÐÌí¼ÓÄúµÄ Laravel Ó¦ÓóÌÐòµÄ¸ù URL£¬²¢·µ»ØͼÏñµÄÍêÕû URL¡£
½áÂÛ
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏêϸÏÈÈÝÁËÔÚ Laravel Ó¦ÓóÌÐòÖÐÉèÖÃͼƬµÄÀú³Ì¡£ÎÒÃÇÏàʶÁËÔõÑùʹÓÃÍâµØÎļþϵͳºÍÔÆ´æ´¢À´´¦ÀíͼÏñºÍͼƬ£¬²¢Ê¹Óà Laravel ¿ØÖÆÆ÷ºÍ Blade Ä£°åÒýÇæÏÔʾËüÃÇ¡£ÔÚÄúµÄÏÂÒ»¸ö Laravel ÏîÄ¿ÖУ¬Äú¿ÉÒÔʹÓÃÕâЩÊÖÒÕÀ´Ìí¼ÓͼÏñºÍͼƬ£¬²¢ÈÃÄúµÄÓ¦ÓóÌÐòÔ½·¢¸»ºñºÍÎüÒýÈË¡£
ÒÔÉϾÍÊÇlaravelͼƬÔõôÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡