javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JavaScript图片预览

基于JavaScript实现图片上传前预览功能

作者:叫我一声阿雷吧

这篇文章主要介绍了如何手把手实现一个实用的 JS 图片上传前预览功能,支持多图选择、格式 / 大小校验、预览图删除等核心功能,感兴趣的小伙伴可以参考一下

案例核心效果

实现思路(极简清晰)

分 3 步落地,逻辑简单易上手,零基础也能快速掌握:

完整源码(可直接复制运行)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS 图片上传前预览 | 实战案例</title>
    <style>
        /* 全局重置(精简规范) */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", sans-serif;
        }
        /* 页面布局:居中显示 */
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 40px 20px;
            background-color: #f5f5f5;
        }
        /* 标题样式 */
        .title {
            font-size: 24px;
            color: #333;
            margin-bottom: 30px;
            text-align: center;
        }
        /* 上传容器 */
        .upload-container {
            width: 100%;
            max-width: 800px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        /* 自定义上传按钮 */
        .upload-btn-wrapper {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }
        .custom-upload-btn {
            padding: 12px 24px;
            font-size: 16px;
            color: #fff;
            background-color: #409eff;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .custom-upload-btn:hover {
            background-color: #66b1ff;
        }
        /* 隐藏原生文件输入框 */
        #fileInput {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        /* 提示文本 */
        .tip-text {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
        }
        /* 预览区域 */
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        /* 预览项 */
        .preview-item {
            position: relative;
            width: 150px;
            height: 150px;
            border-radius: 6px;
            overflow: hidden;
            border: 1px solid #eee;
        }
        /* 预览图片 */
        .preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        /* 删除按钮 */
        .delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 24px;
            height: 24px;
            background-color: rgba(245, 108, 108, 0.8);
            color: #fff;
            border: none;
            border-radius: 50%;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            display: none;
        }
        .preview-item:hover .delete-btn {
            display: block;
        }
        .delete-btn:hover {
            background-color: #f56c6c;
        }
        /* 错误提示 */
        .error-tip {
            color: #f56c6c;
            font-size: 14px;
            margin-top: 10px;
        }
        /* 移动端适配 */
        @media (max-width: 500px) {
            .title {
                font-size: 20px;
            }
            .preview-item {
                width: calc(50% - 7.5px);
                height: 120px;
            }
            .custom-upload-btn {
                padding: 10px 20px;
                font-size: 15px;
            }
        }
    </style>
</head>
<body>
    <h1 class="title">图片上传前预览功能</h1>
    <div class="upload-container">
        <!-- 自定义上传按钮 -->
        <div class="upload-btn-wrapper">
            <button class="custom-upload-btn">选择图片</button>
            <input type="file" id="fileInput" accept="image/jpeg,image/png,image/webp" multiple>
        </div>
        <p class="tip-text">支持格式:jpg/png/webp | 单张图片最大:5MB | 可多选</p>
        <div class="error-tip" id="errorTip"></div>
        <!-- 预览区域 -->
        <div class="preview-container" id="previewContainer"></div>
    </div>
    <script>
        // 1. 获取DOM元素
        const fileInput = document.getElementById('fileInput');
        const previewContainer = document.getElementById('previewContainer');
        const errorTip = document.getElementById('errorTip');
        // 配置项
        const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp']; // 允许的图片格式
        const MAX_SIZE = 5 * 1024 * 1024; // 最大5MB
        // 2. 初始化:监听文件选择事件
        fileInput.addEventListener('change', handleFileSelect);
        // 3. 处理文件选择逻辑
        function handleFileSelect(e) {
            // 清空错误提示
            errorTip.textContent = '';
            // 获取选中的文件列表
            const files = e.target.files;
            if (!files.length) return;
            // 遍历文件列表
            Array.from(files).forEach(file => {
                // 校验文件格式
                if (!ALLOWED_TYPES.includes(file.type)) {
                    errorTip.textContent += `文件${file.name}格式不支持,仅支持jpg/png/webp!\n`;
                    return;
                }
                // 校验文件大小
                if (file.size > MAX_SIZE) {
                    errorTip.textContent += `文件${file.name}超过5MB限制!\n`;
                    return;
                }
                // 读取文件并生成预览图
                generatePreview(file);
            });
            // 清空文件输入框(解决重复选择同一文件不触发change事件的问题)
            fileInput.value = '';
        }
        // 4. 生成预览图(核心逻辑)
        function generatePreview(file) {
            // 创建FileReader对象读取文件
            const reader = new FileReader();
            // 读取完成回调
            reader.onload = function(e) {
                // 创建预览项容器
                const previewItem = document.createElement('div');
                previewItem.className = 'preview-item';
                previewItem.dataset.fileName = file.name;
                // 创建预览图片
                const previewImg = document.createElement('img');
                previewImg.className = 'preview-img';
                previewImg.src = e.target.result; // 设置图片源为文件Base64编码
                previewImg.alt = file.name;
                // 创建删除按钮
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'delete-btn';
                deleteBtn.textContent = '×';
                // 绑定删除事件
                deleteBtn.addEventListener('click', () => {
                    previewItem.remove();
                });
                // 组装预览项
                previewItem.appendChild(previewImg);
                previewItem.appendChild(deleteBtn);
                // 添加到预览区域
                previewContainer.appendChild(previewItem);
            };
            // 以DataURL格式读取文件
            reader.readAsDataURL(file);
        }
    </script>
</body>
</html>

核心代码拆解(重点突出,易懂好记)

1. HTML 结构(极简规整)

核心分为 3 部分,功能边界清晰:

2. CSS 样式(简约美观,交互友好)

重点关注 3 个核心样式:

3. JS 逻辑(核心中的核心,分步拆解)

文件校验

文件读取

交互优化

兼容性

新手常见踩坑点(精准避坑,少走弯路)

扩展思路(落地性强,新手可练)

核心知识点总结(凝练精准,实战导向)

到此这篇关于基于JavaScript实现图片上传前预览功能的文章就介绍到这了,更多相关JavaScript图片预览内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文