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代码
$uid = Session::get("member_id"); $extension = $request->file('file')->extension(); // 上传文件扩展名 $time = time(); $path = $request->file('file')->storeAs('avatars', "$time.$extension");//上传图片 $url = "/uploads/".$path; DB::table("users")->where(['uid'=>$uid])->update(['users_img'=>$url]); return response()->json(['code'=>0,'img'=>$url]);
4.laravel 默认上传图片的地址没有默认在public里面 需要修改配置文件
4.1默认图片上传地址
此时的文件不能直接访问,修改配置文件
再次上传
$extension = $request->file('avatar')->extension(); // 上传文件扩展名
$name = $request->file('avatar')->getClientOriginalName();// 获取原始文件名