layui文件上传+ThinkPHP
1.前端html代码
<div class="layui-form-item">
<label class="layui-form-label">修改头像</label>
<div class="layui-input-inline uploadHeadImage">
<div class="layui-upload-drag" id="headImg">
<i class="layui-icon"></i>
<p>点击上传图片,或将图片拖拽到此处</p>
</div>
</div>
<div class="layui-input-inline">
<div class="layui-upload-list">
<img class="layui-upload-img headImage" src="" id="demo1">
<p id="demoText"></p>
</div>
</div>
</div>
2.前端js代码
<script>layui.use(['form', 'layer','upload',"element"],
function() {
$ = layui.jquery;
var form = layui.form,
upload = layui.upload,
layer = layui.layer;
//拖拽上传
var uploadInst = upload.render({
elem: '#headImg'
, url: '{:url("uploadImg")}'
, size: 500
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#demo1').attr('src', result); //图片链接(base64)
});
}
, done: function (res) {
console.log(res);
//如果上传失败
if (res.code > 0) {
return layer.msg('上传失败');
}
var demoText = $('#demoText');
// demoText.html('<span style="color: #8f8f8f;">上传成功!!!</span>');
$("#imagepath").val(res.image)
layer.msg("上传成功")
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
}
});
element.init();
});
3.后台php代码
// 图片上传
public function uploadImg(){
// 上传代码
$file = request()->file('file');
// 上传到本地服务器
$savename = \think\facade\Filesystem::disk('public')->putFile( 'goods', $file);
$data['image'] = $savename;
$data['code'] = 0;
return json($data);
}
本文来自博客园,作者:公子初心,转载请注明原文链接:https://www.cnblogs.com/ixuhui/p/15723085.html