纯js图片上传插件

一、效果预览

支持多图片上传,删除、预览。
在这里插入图片描述

二、使用简单

  1. 导入依赖(需要依赖jquery)
<link th:href="@{/css/index.css}" rel="stylesheet"/>

<!--三方依赖-->
<script th:src="@{/js/jquery.min.js}"></script>
<!--<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>-->

<script th:src="@{/js/index.js}"></script>
  1. 绑定图片容器
<div id="img1" style="width: 205px">

</div>
const img1 = new imgFactory('img1', [], [], []);
  1. 初始化容器
 img1.init()
  1. 上传图片
//上传图片
var data={
     url:'/common/uploads',
     //上传接口文件参数名
     fileParamName:'files'
 }
 img1.upload(data,"img1",function (res) {
	 if (res.isSuccess){
	 
	 }
 })

三、完整代码

(一)index.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>上传图片(拍照上传、图库上传)</title>
    <link th:href="@{/css/index.css}" rel="stylesheet"/>
</head>
<body style="background-color: #F2F2F2">

<div>
    <div id="img1" style="width: 205px">

    </div>
    <div id="img2">

    </div>
</div>
<div>
    <button type="button" id="upload">上传</button>
</div>
<!--三方依赖-->
<script th:src="@{/js/jquery.min.js}"></script>
<!--<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>-->
<script th:src="@{/js/index.js}"></script>
<script>
    //初始化图片容器
    const img1 = new imgFactory('img1', [], [], []);
    img1.init()
    const img2 = new imgFactory('img2', [], [], []);
    img2.init()

    $('#upload').click(function () {
        //上传图片
        var data={
            url:'/common/uploads',
            //上传接口文件参数名
            fileParamName:'files'
        }
        img1.upload(data,"img1",function (res) {
            if (res.isSuccess){
                console.log(res.res)
                img2.upload(data,"img2",function (res) {
                    if (res.isSuccess){
                        console.log(res.res)
                    }
                })
            }
        })
    })
</script>
</body>
</html>

(二)css

ul {
    list-style-type: none; /* 移除项目标记 */
    padding: 0; /* 移除内边距 */
    margin: 0; /* 移除外边距 */
}
.upload-content {
    font-size: 12px;
    color: #666;
    padding: 20px;
    background: #fff;
    margin-bottom: 15px ;
    text-align: left;
}

.upload-content .content-img-list {
    display: inline;
}

.upload-content .content-img .ico-plus {
    display: inline-block;
    vertical-align: middle;
    margin-top: -4px;
    margin-left: 2px;
    width: 28px;
    height: 28px;
}

.upload-content .content-img-list-item {
    position: relative;
    display: inline-block;
    width: 165px;
    height: 96px;
    margin-top: 20px;
}
.upload-content .content-img-list-item .hide {
    display: none;
}

.upload-content .content-img-list-item .delete-btn {
    position: absolute;
    left: 0;
    bottom: 0;
    text-align: center;
    width: 100%;
    background: rgba(0, 0, 0, 0.6);
    height: 28px;
    line-height: 28px;
    color: #fff;
    cursor: pointer;
}

.upload-content .content-img-list-item .ico-delete {
    display: inline-block;
    vertical-align: middle;
    width: 12px;
    height: 13px;
}

.upload-content .content-img-list-item img {
    width: 165px;
    height: 96px;
}

.upload-content .upload-tips {
    padding-top: 10px;
    text-align: right;
    width: 100%;
}

/*图片上传按钮*/
.upload-content .file {
    position: relative;
    /*display: inline-block;*/
    border: 1px dashed #DEDEDE;
    border-radius: 4px;
    color: #999999;
    text-decoration: none;
    text-indent: 0;
    width: 165px;
    height: 96px;
    line-height: 96px;
    text-align: center;
}

.upload-content .file input {
    position: absolute;
    font-size: 0px;
    right: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
    width: 165px;
    height: 96px;
}

.upload-content .file:hover {
    color: #999999;
}

.upload-submit {
    text-align: center;
    margin-top: 50px;
}

.upload-submit .btn-submit-upload {
    display: inline-block;
    width: 170px;
    height: 40px;
    text-align: center;
    line-height: 38px;
    font-size: 14px;
    box-sizing: border-box;
    background: #ff8819;
    color: #fff;
    border: 1px solid #ff8819;
    border-radius: 2px;
    text-decoration: none;
}

(三)js

$(function () {
    // 鼠标经过显示删除按钮
    $('.content-img-list').on('mouseover', '.content-img-list-item', function () {
        $(this).children('a').removeClass('hide');
    });
    // 鼠标离开隐藏删除按钮
    $('.content-img-list').on('mouseleave', '.content-img-list-item', function () {
        $(this).children('a').addClass('hide');
    });
});
class imgFactory {
    /**
     * 
     * @param elem 容器id
     * @param imgFile 文件,从input中获取 (数组)
     * @param imgSrc 用于预览图片的可访问的本地url (数组)
     * @param imgName 图片名 (数组)
     */
    constructor(elem, imgFile, imgSrc, imgName) {
        this.elem = elem;
        this.imgFile = imgFile;
        this.imgSrc = imgSrc;
        this.imgName = imgName;
    }
    
    init() {
        //绑定图片上传
        var that = this;
        var imgBox = 'content-img-list-' + that.elem;
        var upload = this.elem + "-upload";
        //创建img插件
        // 创建一个带有类名的 p 元素
        var newParagraph = '<div class="upload-content">\n' +
            '    <div class="content-img">\n' +
            '        <div class="file">\n' +
            '           <span class="mui-icon mui-icon-plusempty" style="font-size: 16px"></span>上传图片,支持jpg/png<input type="file" multiple name="file" accept="image/*" id="' + upload + '" >\n' +
            '        </div>\n' +
            '        <ul class="content-img-list" id="' + imgBox + '">\n' +
            '        </ul>\n' +
            '    </div>\n' +
            '</div>';

        // 将这个 p 元素添加到文档中的某个特定元素之后
        $('#' + that.elem).html(newParagraph);

        $('#' + upload).on('change', function () {

            // if(imgSrc.length>=4){
            // 	return alert("最多只能上传4张图片");
            // }
            var imgSize = this.files[0].size;  //b
            // if(imgSize>1024*1024*10){//1M
            // 	return alert("上传图片不能超过1M");
            // }
            // console.log(this.files[0].type)
            // if(this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif'){
            // 	return alert("图片上传格式不正确");
            // }

            var fileList = this.files;
            for (var i = 0; i < fileList.length; i++) {
                var imgSrcI = that.getObjectURL(fileList[i]);
                that.imgName.push(fileList[i].name);
                that.imgSrc.push(imgSrcI);
                that.imgFile.push(fileList[i]);
            }
            // if(imgSrc.length==10){//隐藏上传按钮
            // 	$('.content-img .file').hide();
            // }
            that.addNewContent(imgBox, that);
            this.value = null;//解决无法上传相同图片的问题
        })

        // 单个图片删除
        $(".content-img-list").on("click", '.content-img-list-item a', function () {
            var index = $(this).attr("index");
            that.imgSrc.splice(index, 1);
            that.imgFile.splice(index, 1);
            that.imgName.splice(index, 1);
            that.addNewContent(imgBox, that);
            // if (that.imgSrc.length < 4) {//显示上传按钮
            // 	$('.content-img .file').show();
            // }
        });
    }

    //建立一个可存取到改file的url
    getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    addNewContent(obj, that) {
        // console.log(that.imgSrc)
        // console.log(obj)
        $("#" + obj).html("");
        for (var a = 0; a < that.imgSrc.length; a++) {
            var oldBox = $("#" + obj).html();
            // console.log(oldBox)
            $("#" + obj).html(oldBox + '<li class="content-img-list-item"><img src="' + that.imgSrc[a] + '" alt="" data-preview-src="" data-preview-group="'+obj+'"><a index="' + a + '" class="hide delete-btn"><i class="mui-icon mui-icon-trash">删除图标</i></a></li>');
        }
    }
    /**
     * @param request 上传接口配置
     * @param msg 提示信息
     * @param callback 上传后回调函数 -> 实例
     * function (data) {
     *    if (data.isSuccess){
     *        //上传成功,获取上传结果data.res
     *        console.log(data.res)
     *    }
     * }
     *
     */
    upload(request,msg,callback){
        var formFile = new FormData();
        
        if (this.imgFile.length===0){
            var data={}
            data.isSuccess = true 
            data.msg = "上传成功,没有选择图片"
            data.res = {};
            callback(data)
        }
        // 遍历图片imgFile添加到formFile里面
        $.each(this.imgFile, function (i, file) {
            formFile.append(request.fileParamName, file);
        });
        $.ajax({
            url: request.url,
            type: 'POST',
            data: formFile,
            //异步上传,通过回调函数获取上传结果
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function (res) {
                if (res.code === 0) {
                    //alert("上传成功")
                    console.log(msg+',上传成功!');
                    var data={}
                    data.isSuccess = true
                    data.msg = "上传成功"
                    data.res = res;
                    callback(data)
                } else {
                    console.log(msg+',上传失败!');
                    var data={}
                    data.isSuccess = false
                    data.msg = "上传失败"
                    data.res = res;
                    callback(data)
                }
            }
        })
    }
}

四、附带后台上传文件代码

spring boot 项目,新增图片全屏预览

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值