原生es6+sortable.js多图排序上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Layui + Sortable.js 图片排序上传</title>
    <link href="//unpkg.com/layui@2.9.21-rc.3/dist/css/layui.css" rel="stylesheet">
    <script src="//unpkg.com/layui@2.9.21-rc.3/dist/layui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
    <style>
        .sortable {
            list-style-type: none;
            margin: 0;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
        }

        .sortable li {
            margin: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            display: inline-block;
            width: 100px;
            text-align: center;
            cursor: move;
            position: relative;
            box-sizing: border-box;
        }

        .sortable img {
            width: 100%;
            height: 80px;
            object-fit: cover;
        }

        .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(255, 0, 0, 0.5);
            color: white;
            padding: 2px 5px;
            border-radius: 50%;
            cursor: pointer;
        }
    </style>
</head>
<body>

<div class="layui-container">
    <h3>上传并排序图片</h3>

    <div class="layui-upload">
        <button type="button" class="layui-btn" id="upload-btn">选择图片</button>
        <input type="file" id="file-upload" style="display:none" multiple="multiple">
    </div>

    <ul id="sortable" class="sortable"></ul>

    <button id="submit-btn" class="layui-btn">上传排序后的图片</button>
</div>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const uploadBtn = document.getElementById('upload-btn');
        const fileInput = document.getElementById('file-upload');
        const sortableList = document.getElementById('sortable');
        const submitBtn = document.getElementById('submit-btn');

        // 监听上传按钮点击
        uploadBtn.addEventListener('click', () => fileInput.click());

        // 监听文件选择框变化
        fileInput.addEventListener('change', ({ target: { files } }) => {
            if (files.length) {
                Array.from(files).forEach(file => {
                    const reader = new FileReader();
                    reader.onload = ({ target: { result } }) => {
                        const imgElement = document.createElement('li');
                        imgElement.classList.add('sortable-item');
                        imgElement.innerHTML = `
                        <img src="${result}" alt="图片预览" class="img-preview" data-id="${file.name}" />
                        <span class="remove-btn">×</span>`;
                        sortableList.appendChild(imgElement);
                    };
                    reader.readAsDataURL(file);
                });
            }
        });

        // 初始化 sortable.js 使图片可以拖拽排序
        new Sortable(sortableList, { animation: 150 });

        // 监听删除按钮事件
        sortableList.addEventListener('click', (event) => {
            if (event.target.classList.contains('remove-btn')) {
                event.target.closest('li').remove();
            }
        });

        // 提交排序后的图片
        submitBtn.addEventListener('click', async () => {
            const formData = new FormData();
            const images = [...sortableList.querySelectorAll('li img')];

            for (const [index, img] of images.entries()) {
                try {
                    const res = await fetch(img.src);
                    const blob = await res.blob();

                    // 获取 MIME 类型,并确定文件扩展名
                    const extension = blob.type.split('/')[1];  // 获取 'jpeg' 或 'png'
                    const fileName = `image_${index + 1}.${extension}`;

                    formData.append('images[]', blob, fileName);
                } catch (error) {
                    console.error('Blob 转换失败:', error);
                    return;
                }
            }

            await uploadFiles(formData);
        });

        // 上传文件到后端
        const uploadFiles = async (formData) => {
            try {
                const response = await fetch('/index/upload/upload/', { method: 'POST', body: formData });
                const data = await response.json();
                alert(data.code === 200 ? '上传成功!' : '上传失败!');
            } catch (error) {
                console.error('上传失败:', error);
                alert('上传失败,请重试!');
            }
        };
    });

</script>

</body>
</html>

采用了es2024最新版本的语法,简化、优化了代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值