您现在的位置是: 网站首页> PHP> Laravel Laravel
Laravel实现前端上传base64图片
Smile 2020-12-29 17:26:15 PHP Javascript Laravel 阅读:2380
简介前端需要开发一个用户反馈的简单功能,使用cupload.js插件上传用户反馈的截图以及预览功能,后端使用Laravel框架接收,亲测可用
1、下载cupload.js插件并引入
2、前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="./static/js/cupload.js"></script>
<title>用户投诉</title>
<style>
.main {margin: 0 30px;padding: 20px 0;}
.text {width: 100%;height: 150px;resize: none;line-height: 25px;border: none;font-size: 16px;border-bottom: 1px solid #eee;}
.content {position: relative;}
.maxnumber {position: absolute;right: 8px;bottom: 15px;}
.screenshot {border-bottom: 1px solid #eee;}
.screenshot p {color: #333;font-size: 18px;margin: 20px 0;}
.url p {margin: 15px 0;font-size: 18px;color: #333;}
.url input {border-bottom: 1px solid #eee;line-height: 25px;width: 100%;}
::-webkit-input-placeholder {color: #d4d4d4 !important;font-size: 14px;}
.sumbit {width: 100%;text-align: center;}
.sumbit span {margin: 50px auto;text-align: center;width: 180px;height: 35px;line-height: 35px;display: block;background-color: #e5e5e5;border-radius: 5px;}
</style>
</head>
<body>
<div class="main">
<form id="form">
<div class="content">
<textarea class="text" name="content" placeholder="请输入投诉描述" maxlength="200"></textarea>
<div class="maxnumber"> 0/200</div>
</div>
<div class="screenshot">
<p>证据截图(最多四张)</p>
<div id="cupload-2"></div>
</div>
<div class="sumbit">
<span>提交</span>
</div>
</form>
</div>
</body>
<script>
//实例化cupload对象
var cupload2 = new Cupload({
ele: '#cupload-2',
num: 4,
url: '{{route("upload")}}', //异步上传url,非必需,无默认值
deleteUrl: '{{route("delUpload")}}', //删除url,删除时同时删除服务器图片
width: 130,
height: 130,
maxSize: 2048,
});
</script>
</html>
3、后台代码
(1)上传接口
引入 use Illuminate\Support\Facades\Storage;
public function upload(Request $request)
{
$image = $request->get('image'); // your base64 encoded
preg_match('/^(data:\s*image\/(\w+);base64,)/',$image,$res);
$image = str_replace($res[1],'', $image);
$image = str_replace(' ', '+', $image);
$imagePath= 'gbook/'.time().mt_rand(1000,9999).'.'.$res[2];
$webPath = '/storage/' . $imagePath;
Storage::disk('public')->put($imagePath, base64_decode($image));
return $webPath;
}
(2)删除接口
public function delUpload(Request $request)
{
$path = $request->get('image');
$res = unlink('.'.$path);
}
注:$image = str_replace(' ', '+', $image);这行代码很关键,不然上传保存成功之后,图片是损坏的打不开
很赞哦! (0)