laravel5.6上传图片及显示
Posted 休夸此地分天下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel5.6上传图片及显示相关的知识,希望对你有一定的参考价值。
借鉴大神博客:https://blog.csdn.net/tony_110/article/details/80105099
文档:laravel5.6文档 文件传输
在config下新建文件admin.php,定义上传文件的路径
‘upload_img_path‘ =>‘app/public/img‘,//本地上传图片路径
‘upload_file_path‘ =>‘app/public/files‘//本地上传文件路径
在config/filesystems.php下定义
‘disks‘ => [
‘uploadimg‘=>[
‘driver‘=>‘local‘,
‘root‘=>storage_path(config(‘admin.upload_img_path‘))
],
‘uploadfiles‘=>[
‘driver‘=>‘local‘,
‘root‘=>storage_path(config(‘admin.upload_file_path‘))
],
‘local‘ => [
‘driver‘ => ‘local‘,
‘root‘ => storage_path(‘app‘),
],
‘public‘ => [
‘driver‘ => ‘local‘,
‘root‘ => storage_path(‘app/public‘),
‘url‘ => env(‘APP_URL‘).‘/storage‘,
‘visibility‘ => ‘public‘,
],
‘s3‘ => [
‘driver‘ => ‘s3‘,
‘key‘ => env(‘AWS_KEY‘),
‘secret‘ => env(‘AWS_SECRET‘),
‘region‘ => env(‘AWS_REGION‘),
‘bucket‘ => env(‘AWS_BUCKET‘),
],
前端显示
{{ html()->form(‘POST‘, route(‘frontend.repair.repair.upload‘))
->attribute(‘enctype‘, ‘multipart/form-data‘)->attribute(‘files‘, ‘ture‘)->class(‘form-horizontal‘)->open() }}
(红色标注的很重要)
Controller中
use IlluminateSupportFacadesStorage;
public function sendmsg(SendmsgRequest $request)
{
$file = $request->file(‘cover‘);
//保存图片begin
$rule = [‘jpg‘, ‘png‘, ‘gif‘];
if ($request->hasFile(‘cover‘)) {//验证是否上传图片
$clientName = $file->getClientOriginalName();// 文件原名
$tmpName = $file->getFileName();
$realPath = $file->getRealPath();//临时文件的绝对路径
$entension = $file->getClientOriginalExtension();// 扩展名
if (!in_array($entension, $rule)) {
return ‘图片格式为jpg,png,gif‘;
}
$newName = md5(date("Y-m-d H:i:s") . $clientName) . "." . $entension;//图片重命名
$bool = Storage::disk(‘uploadimg‘)->put($newName, file_get_contents($realPath));//保存图片
//return back();
//return json_encode([‘status‘ => 1, ‘filepath‘ => $newName]);
} else {
$idCardFrontImg = ‘‘;
//return json_encode($idCardFrontImg);
$newName=1;
}
//保存图片end
}
根据文档中的要求composer安装了三项东西。
显示时:
<th><img src="/storage/img/pic_name"></th><!--根据数据库中报存的图片名称显示图片-->
以上是关于laravel5.6上传图片及显示的主要内容,如果未能解决你的问题,请参考以下文章