如何在layui中的表格中,实现图片上传?每次点击产生的新的一行里面又可以上传?

新手上路,请多包涵

我想在layui的表格里面制作一个上传图片的功能,可以回显看图片,也能修改图片。本人是java开发,对于前端不是很了解。不知道改怎么弄
image.pngimage.png

<div class="col-sm-12" id="specTableDiv2">
                    <h3><span class="must">*</span><span style="margin-right: 200px">奖项设置:</span><span class="must ">图片尺寸为100*100</span></h3>
                    <button type="button" class="btn btn-primary" onclick="addSpec2()">新增奖项</button>
                    <table class="layui-table" id="specTable2"></table>
                </div>
function addSpec2() {
    console.log("fdfd1123123")
    // 增加空数据行
    specTable2.addById({
        id : new Date().getTime(),
        specName : "",
        specNumber : "1",
        specUnit : "份",
        unitId : "31",
        specNo : "",
        specSubno : "",
        isBarcode : "1",
        itemPrePrice : "",
        costPrice : "",
        firstCitySalePrice : "",
        secondCitySalePrice : "",
        producedDate : "",
        expirationDate : "",
        expirationDateType : "年",
        salesInventory : "",
        prizeType: "",
        prizeName: "",
        prizePic: "",
        stockNum: "",
    })
    // 重新加载表格
    reloadTable2();
    $(".layui-table-body").css('overflow','visible');
    $(".layui-table-box").css('overflow','visible');
    $(".layui-table-view").css('overflow','visible');



}
function reloadTable2() {
    mainTable2.reload({data: specTable2.getAll()})
    $('.layui-input-date').each(function () {
        let shelf = this;
        laydate.render({
            elem: this,
            format: 'yyyy-MM-dd',
            type: 'date',
            trigger: 'click',
            done: function (value, date, endDate) {
                let id = $(shelf).data("id");
                let field = $(shelf).data("field");
                // 更新数据
                let item = specTable2.getById(id);
                item[field] = value;
                specTable2.updateById(item);
            }
        });
    });
}
let col2 = [
        {field: '', title: '序号', type: 'numbers', width: 112},
        {
            field: 'prizeType', title: '奖品类型', width : 120, templet: function (row) {
                let dates = ['未中奖', '实物商品', '优惠券'];
                let date = dates.indexOf(row.expirationDateType);
                let options = '';
                for (let i = 0; i < dates.length; i++) {
                    if (i === date) {
                        options += `<option value="${dates[i]}" selected>${dates[i]}</option>`
                    } else {
                        options += `<option value="${dates[i]}">${dates[i]}</option>`
                    }
                }
                if (row.synState === '1') {
                    return dates[date];
                }
                return `<div class="title-event" title="与实物一致, 不一致拒收并处罚"><select class="form-control" lay-filter="prizeType" data-id="${row.id}" data-field="prizeType" onchange="changeExpirationDateType()">${options}</select></div>`
            }
        },
        {
            field: 'prizeName', title: '奖品名称', width : 120,templet: function (row) {
                if (row.synState === '1') {
                    return row.specName + '&nbsp;&nbsp;<span style="color: green;font-weight: bolder">(已传输产品库)</span>';
                }
                return '<input type="text" class="layui-input title-event" title="输入要与包装一致, 要有包装单位 (/袋)" placeholder="请输入奖品名称"  data-id="' + row.id + '" data-field="prizeName" value="' + row.prizeName + '" />'
            }
        },
        {
            field: 'prizePic', title: '奖品图片', width : 120,templet: function (row) {
                if (row.synState === '1') {
                    return row.specName + '&nbsp;&nbsp;<span style="color: green;font-weight: bolder">(已传输产品库)</span>';
                }else {
                    var uniqueId = 'upload-' + row.id; // 生成一个唯一的ID
                    return '<input type="file" class="layui-upload-file" id="' + uniqueId + '" name="file" accept="image/*" onchange="uploadPrizePic(\'' + row.id + '\', this);" />';
                }
            }
        },
        {
            field: 'stockNum', title: '库存数量', width : 120,templet: function (row) {
                if (row.synState === '1') {
                    return row.specName + '&nbsp;&nbsp;<span style="color: green;font-weight: bolder">(已传输产品库)</span>';
                }
                return '<input type="text" class="layui-input title-event" title="输入要与包装一致, 要有包装单位 (/袋)" placeholder="请输入规格名称"  data-id="' + row.id + '" data-field="stockNum" value="' + row.stockNum + '" />'
            }
        },


    ];
    mainTable2 = table.render({
        elem: '#specTable2',
        cols: [col2],
        data: [], // 数据源
        page: true,

    });
var specTable = new DataBase();
var specTable2 = new DataBase();
var mainTable = null;
var mainTable2 = null;
class DataBase {
    /**
     * 数据列表
     * @type {[]}
     */
    list = [];
    /**
     * 主键索引
     * @type {{}}
     */
    idIndex = {};
    /**
     * 自提点数据库主键
     * @type {string}
     */
    primary = 'id';
    /**
     * 设置自定义主键名称, 默认id
     * @param primary
     */
    setPrimary(primary) {
        this.primary = primary;
    }
    /**
     * 使用数据初始化
     * @param list
     */
    init(list) {
        for (let i = 0; i < list.length; i++) {
            this.list[i] = list[i];
            this.idIndex[list[i][this.primary]] = i;
        }
    }
    /**
     * 添加数据
     * @param data
     */
    addById(data) {
        let id = data[this.primary];
        if (this.idIndex[id] !== undefined && this.idIndex[id] !== -1) {
            this.updateById(data);
            return;
        }
        this.idIndex[id] = this.list.push(data) - 1;
    }

    /**
     * 根据主键删除数据
     * @param id
     */
    deleteById(id) {
        let index = this.idIndex[id];
        this.idIndex[id] = -1;
        this.list[index] = false;
    }

    /**
     * 根据条件删除数据
     * @param field //{id : 1, xxx: 11}
     */
    deleteByWhere(field = {}) {
        listFor:
        for (let i = 0; i < this.list.length; i++) {
            let item = this.list[i];
            if (item) {
                for(let key in field){
                    if (field[key] != item[key]) {
                        continue listFor;
                    }
                }
                this.idIndex[item[this.primary]] = -1;
                this.list[i] = false;
            }
        }
    }

    /**
     * 更新数据
     * @param data
     */
    updateById(data) {
        let id = data[this.primary];
        this.list[this.idIndex[id]] = data;
    }

    /**
     * 获取数据
     * @param id
     * @returns {*}
     */
    getById(id) {
        return this.list[this.idIndex[id]];
    }

    /**
     * 获取全部数据列表
     * @returns {[]}
     */
    getAll() {
        let res = [];
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i]) {
                res.push(this.list[i]);
            }
        }
        return res;
    }

    /**
     * 获取全部id集合列表
     * @returns {[]}
     */
    getAllIds() {
        let res = [];
        for (let i = 0; i < this.list.length; i++) {
            if (this.list[i]) {
                res.push(this.list[i][this.primary]);
            }
        }
        return res;
    }

    /**
     * 清除所有
     */
    clear() {
        this.idIndex = {};
        this.list = [];
    }
}

这是相关的代码,有哪位前端大佬能指点下

搜素过相关文章,都没解决,文心一言这种ai也问了,没啥用

阅读 483
1 个回答
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Layui</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src/dist/css/layui.css">
</head>
<body>
    <div class="layui-container">
        <button id="addRowBtn" class="layui-btn layui-btn-normal">新增一行</button>
        <table id="imageTable" class="layui-table" lay-size="sm">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>图片</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tableBody">
               
            </tbody>
        </table>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/layui-src/dist/layui.all.js"></script>
    <script>
        layui.use(['upload'], function () {
            const upload = layui.upload;

            let rowIndex = 1; 

            
            document.getElementById('addRowBtn').addEventListener('click', function () {
                const tableBody = document.getElementById('tableBody');
                
               
                const newRow = `
                    <tr>
                        <td>${rowIndex}</td>
                        <td>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary upload-btn" id="uploadBtn${rowIndex}">
                                <i class="layui-icon">&#xe67c;</i> 上传图片
                            </button>
                            <div id="preview${rowIndex}" style="margin-top: 5px;"></div>
                        </td>
                        <td><button class="layui-btn layui-btn-danger layui-btn-sm delete-btn">删除</button></td>
                    </tr>
                `;

               
                tableBody.insertAdjacentHTML('beforeend', newRow);

                
                bindUpload(`uploadBtn${rowIndex}`, `preview${rowIndex}`);
                
                rowIndex++; 
            });

            // 绑定上传组件
            function bindUpload(uploadBtnId, previewId) {
                upload.render({
                    elem: `#${uploadBtnId}`, 
                    url: '/upload', 
                    accept: 'images', 
                    acceptMime: 'image/*', 
                    exts: 'jpg|png|gif|jpeg', 
                    done: function (res) {
                     
                        if (res.code === 0) {
                            document.getElementById(previewId).innerHTML = `
                                <img src="${res.url}" style="max-width: 100px; max-height: 100px;" />
                            `;
                        } else {
                            layer.msg('上传失败:' + res.msg, { icon: 5 });
                        }
                    },
                    error: function () {
                        layer.msg('上传接口异常', { icon: 5 });
                    }
                });
            }

      
            document.getElementById('tableBody').addEventListener('click', function (e) {
                if (e.target.classList.contains('delete-btn')) {
                    e.target.closest('tr').remove();
                }
            });
        });
    </script>
</body>
</html>

这个?好像不能预览上传图,得看看上传成功后的效果,

文档是上传成功后的回调

upload.render({
    elem: `#${uploadBtnId}`, 
    url: '/upload', 
    accept: 'images',
    acceptMime: 'image/*', 
    exts: 'jpg|png|gif|jpeg', 
    done: function (res) {
        // 上传成功回调
        if (res.code === 0) {
            // 预览图片区域显示上传成功的图片
            document.getElementById(previewId).innerHTML = `
                <img src="${res.url}" style="max-width: 100px; max-height: 100px;" />
            `;
        } else {
            layer.msg('上传失败:' + res.msg, { icon: 5 });
        }
    },
    error: function () {
        layer.msg('上传接口异常', { icon: 5 });
    }
});

好像是这么操作吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏