Home > Article > Backend Development > How to use php and layui to implement image upload and preview code
This article introduces you to the code about how to use PHP and layui to upload and preview images. It has a good reference value and I hope it can help friends in need.
End code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload模块快速使用</title> <link rel="stylesheet" href="/layui/css/layui.css" media="all"> </head> <body> <button type="button" class="layui-btn" id="test1"> <i class="layui-icon"></i>上传图片 </button> <div class="layui-upload-list"> <img class="layui-upload-img" width="100px" height="100px" id="demo1"> <p id="demoText"></p> </div> <script src="/layui/layui.js"></script> <script> layui.use('upload', function(){ var $ = layui.jquery ,layer = layui.layer ,upload = layui.upload; var uploadInst = upload.render({ elem:'#test1' ,url:'/index/upload/upload' ,accept:'file' // 允许上传的文件类型 ,auto:true // 自动上传 ,before:function (obj) { // console.log(obj); // 预览 obj.preview(function(index,file,result) { // console.log(file.name); //图片地址 // console.log(file.type); //图片格式 // console.log(file.size); //图片大小 // console.log(file); //图片地址 $('#demo1').attr('src',result); //图片链接 base64 }); } // 上传成功回调 ,done:function(res) { // console.log(upload); console.log(res); if (res.code == 0) { layer.msg(res.msg); }else{ layer.msg(res.msg); } } // 上传失败回调 ,error:function(index,upload) { // 上传失败 } }); }) </script> </body> </html>
php Backend:
public function upload() { $file = request()->file('file'); $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); if($info) { $data['code'] = 0; $data['msg'] = $info->getSaveName(); }else{ $data['code'] = 1; $data['msg'] = $file->getError(); } return json($data); }
Related recommendations:
How does php achieve equal-proportion compression of images?
How does php code in excel files? Converted? How to use php encoding conversion
The above is the detailed content of How to use php and layui to implement image upload and preview code. For more information, please follow other related articles on the PHP Chinese website!