不废话,直接上代码

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <title>上传文件示例</title>
    6. <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css" />
    7. <script src="https://www.layuicdn.com/layui/layui.js"></script>
    8. </head>
    9. <body>
    10. <button id="upload">上传文件</button>
    11. <img />
    12. <script>
    13. layui.use(function() {
    14. var $ = layui.$;
    15. layui.upload.render({
    16. elem: '#upload',
    17. url: '../php/api.php?eventType=upload',
    18. accept: 'images',
    19. progress: function(n, elem) {
    20. layer.msg('正在上传', {
    21. icon: 16,
    22. shade: 0.01,
    23. time: false
    24. });
    25. },
    26. done: function(data) {
    27. layer.msg(data.code, {
    28. icon: data.icon
    29. });
    30. if (data.icon == "1") {
    31. var elem = $("body");
    32. elem.prepend('<img src="' + data.data.host + '">');
    33. }
    34. },
    35. error: function() {
    36. layer.msg('系统出错', {
    37. icon: 2
    38. });
    39. }
    40. });
    41. });
    42. </script>
    43. </body>
    44. </html>