thinkphp5.1+layui实现文件上传

application/admin/controller/Common.php

   /**
     * 文件上传
     * @author Zhang <364322276@qq.com>
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $info = $file->move('uploads');
        if ($info) {
            $result = [
                'code' => 0,
                'msg' => '上传成功',
                'filename' => '/uploads/' . str_replace('\\', '/', $info->getSaveName())

            ];
        } else {
            $result = [
                'code' => -1,
                'msg' => $file->getError()
            ];
        }
        return json($result);
    }

application/admin/view/index/index.html

html

<div class="layui-form-item">
        <label class="layui-form-label">缩略图</label>
        <div class="layui-input-block">
            <img src="{:isset($list.thumb)?$list.thumb:'/images/default.jpg'}" id="preview" width="200">
            <button type="button" class="layui-btn" id="upload"><i class="layui-icon"></i>上传图片
            </button>
            <input type="hidden" name="thumb" value="{:isset($list.thumb)?$list.thumb:'/images/default.jpg'}"
                   class="layui-input layui-input-inline" id="thumb" lay-verify="required">
        </div>
    </div>

script

layui.use(['jquery', 'upload'], function () {
        var $ = layui.jquery,
            upload = layui.upload;
        var uploadInst = upload.render({
            elem: '#upload',
            url: '{:url(\'upload\')}', //地址
            accept: 'images', //类型
            exts: 'jpg|png|gif|bmp|jpeg', //后缀
            done: function (data) {
                if (data.code == 0) {
                    $('#preview').attr('src', data.filename);
                    $('#thumb').val(data.filename);
                    return layer.msg(data.msg);
                }
            },
            error: function () {
                return layer.msg(data.msg);
            }
        });
   });

更多详情:图片/文件上传 – layui.upload

转载请注明来源:开发猿 » thinkphp5.1+layui实现文件上传

赞 (1) 打赏

觉得文章有用就打赏一下哦

支付宝扫一扫打赏

微信扫一扫打赏