Home >Web Front-end >Layui Tutorial >How to use layui to upload images
How to use layui to upload images: first open the html file and reference layui.css and layui.js; then call the front-end html code and set the id value; finally pass "upload.render({ ...})" method to upload images.
The operating environment of this tutorial: Windows 7 system, layui version 2.4. This method is suitable for all brands of computers.
Recommended: "javascript basic tutorial" "layUI tutorial"
Implementation of layui upload function:
1. Go to the official website to download the layui framework
Open the html file and reference layui.css and layui.js
2. Call the front-end html code and set the id value.
<div class="layui-upload upload"> <button type="button" class="layui-form-label" id="upload">上传图片</button> <input class="layui-upload-file" type="file" accept="" name="file"> <div class="layui-upload-list"> <img class="layui-upload-img" id="demo1"> <p id="demoText"></p> </div> </div> <script> layui.use(['laypage', 'layer', 'upload'], function () { var laypage = layui.laypage //设置配置环境 , layer = layui.layer , upload = layui.upload //上传图片 var uploadInst = upload.render({ elem: '#upload' , url: '/upload/' //改成您自己的上传接口 , before: function (obj) { //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { $('#demo1').attr('src', result); //图片链接(base64) }); } , done: function (res) { //如果上传失败 if (res.code > 0) { return layer.msg('上传失败'); } //上传成功 } , error: function () { //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function () { uploadInst.upload(); }); } }); }); </script>
The above is the detailed content of How to use layui to upload images. For more information, please follow other related articles on the PHP Chinese website!