js+css+ajax 多图片一次上传

演示示例

在这里插入图片描述

html

<style>

    /*上传图片插件的样式*/

    .img-box {
        margin-top: 40px;
    }

        .img-box .up-p {
            margin-bottom: 20px;
            font-size: 16px;
            color: #555;
        }

    .z_photo {
        width: 100%;
        padding: 0;
        padding-top: 4px;
        display: flex;
        flex-wrap: wrap;
    }

        .z_photo .z_file {
            position: relative;
            float: left;
        }

    .z_file .file {
        width: 130px;
        height: 130px;
        opacity: 0;
        position: absolute;
        top: 0px;
        left: 0px;
        z-index: 100;
    }

    .z_photo .up-section {
        position: relative;
    }

    .up-section .close-upimg {
        display: block;
        width: 20px;
        height: 20px;
        position: absolute;
        top: 0px;
        right: 0px;
        z-index: 10;
        background: url(/Content/images/a7.png);
        background-size: 100% 100%;
    }

    .up-section:hover {
        border: 1px solid #f15134;
    }

    .z_photo .up-img {
        display: block;
        width: 120px;
        height: 120px;
    }

    .loading {
        border: 1px solid #D1D1D1;
        background: url(/Content/images/loadingNew.gif) no-repeat center;
    }

    .up-opcity {
        opacity: 0;
    }

    .upimg-div .up-section {
        width: 120px;
        height: 120px;
        margin-left: 1px;
        margin-bottom: 1px;
        margin-right: 5px;
    }

    .img-box .upimg-div .z_file {
        width: 120px;
        height: 120px;
    }

    .z_file .add-img {
        display: block;
        width: 120px;
        height: 120px;
        background-image: url(/Content/images/uploadImg.png);
        background-size: 120px;
    }
</style>

<div class="z_photo upimg-div clear" id="IntroSection" onclick="openImg('IntroSection')">
                @*绑定已有数据时添加*@
                @if (!string.IsNullOrEmpty(Model.Intro))
                {
                    foreach (var item in Model.Intro.Split(','))
                    {
                        <div class="up-section fl">
                            <span class="close-upimg"></span>
                            <img class="up-img" src="@item">
                        </div>
                    }
                }
                <section class="z_file fl IntroFile">
                    <span class="add-img"></span>
                    <input type="file" name="file" id="IntroFile" class="file" value="5" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple />
                </section>
            </div>
            
<div class="z_photo upimg-div clear" id="ServiceFlowChartSection" onclick="openImg('ServiceFlowChartSection')">
                @if (!string.IsNullOrEmpty(Model.ServiceFlowChart))
                {
                    foreach (var item in Model.ServiceFlowChart.Split(','))
                    {
                        <div class="up-section fl">
                            <span class="close-upimg"></span>
                            <img class="up-img" src="@item">
                        </div>
                    }
                }
                <section class="z_file fl ServiceFlowChartFile">
                    <span class="add-img"></span>
                    <input type="file" name="file" id="ServiceFlowChartFile" class="file" value="15" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple />
                </section>
            </div>

<script src="imgUpload.js"></script>
<script>
    //获取上传图片src
    function getImag() {
        var intro = $("#IntroSection img");
        var introImg = [];
        for (var i = 0; i < intro.length; i++) {
            introImg.push(intro[i].src)
        }
        return introImg;
    }
    //查看大图
    function openImg(name) {
        
    }
</script>

注意id与class样式名一致

imgUpload.js

$(function () {
    enter_imgTotal = []; //上传的图片arr
    var fileList = [];
    //	图片上传*****************************************
    var delParent;
    var defaults = {
        fileType: ["jpg", "png", "bmp", "jpeg"], // 上传文件的类型
        fileSize: 1024 * 1024 * 10 // 上传文件的大小 10M
    };
    /*点击图片的文本框*/
    $(".file").change(function () {
        var idFile = $(this).attr("id");
        var valueFile = $(this).attr("value");//图片上传最大值
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        fileList = file.files; //获取的图片文件
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length; //总的数量
        if (fileList.length > valueFile || totalNum > valueFile) {
            alert("上传图片数目不可以超过" + valueFile + "个,请重新选择"); //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        } else if (numUp < valueFile) {
            fileList = validateUp(fileList);
            enter_imgTotal.push(fileList);
            if (fileList.length != 0) {
                UploadFile(fileList, idFile);
            }
        }
        setTimeout(function () {
            $(".up-section").removeClass("loading");
            $(".up-img").removeClass("up-opcity");
        }, 450);
        numUp = imgContainer.find(".up-section").length;
        if (numUp >= valueFile) {
            $(this).parent().hide();
        }
    });

    $(".z_photo").delegate(".close-upimg", "click", function () {
        delParent = $(this).parent();
        var numUp = delParent.siblings().length;
        if (enter_imgTotal.length != 0) {
            var aa = delParent.index();
            var delimg_index = enter_imgTotal[0].length - aa - 1;
            enter_imgTotal[0].splice(delimg_index, 1); //删除掉数组对应的图片
        }

        //上传图片最多15张
        if (numUp < 16) {
            delParent.parent().find(".z_file").show();
        }
        delParent.remove();
    });
    
    function validateUp(files) {
        var arrFiles = []; //替换的文件数组
        for (var i = 0, file; file = files[i]; i++) {
            //获取文件上传的后缀名
            var newStr = file.name.split("").reverse().join("");
            if (newStr.split(".")[0] != null) {
                var type = newStr.split(".")[0].split("").reverse().join("");
                if (jQuery.inArray(type, defaults.fileType) > -1) {
                    // 类型符合,可以上传
                    if (file.size >= defaults.fileSize) {
                        alert(file.size);
                        alert('您这个"' + file.name + '"文件大小过大');
                    } else {
                        // 在这里需要判断当前所有文件中
                        arrFiles.push(file);
                    }
                } else {
                    alert('您这个"' + file.name + '"上传类型不符合');
                }
            } else {
                alert('您这个"' + file.name + '"没有类型, 无法识别');
            }
        }
        return arrFiles;
    }

    function UploadFile(fileList, idFile) {
        //图片批量上传
        var formData = new FormData();
        for (let i in fileList) {
            formData.append("files", fileList[i]);
        }
        $.ajax({
            type: "POST",
            url: "/Common/HonorUpload",
            async: false,
            //beforeSend: function (request) {
            //	request.setRequestHeader("Authorization", '123');
            //},
            data: formData,
            cache: false, //上传文件不需要缓存
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            success: function (res) {
                var result = JSON.parse(res);
                if (result.success == true) {
                    var arr = result.imageUrl.split(',');
                    var imgContainer = $("." + idFile); //存放图片的元素
                    for (var i = 0; i < arr.length; i++) {
                        //拼接图片
                        //var imgUrl = window.URL.createObjectURL(fileList[i]);
                        //imgArr.push(imgUrl);
                        var $div = $("<div class='up-section fl loading'>");
                        imgContainer.before($div);
                        var $img0 = $("<span class='close-upimg'>");
                        $img0.appendTo($div);
                        var $img = $("<img class='up-img up-opcity'>");
                        $img.attr("src", arr[i]);
                        $img.appendTo($div);
                    }
                } else {
                    alert("图片上传失败");
                    return false;
                }
            },
            error: function () {
                alert(res.message)
            }
        });
    }
})

后端接口

[HttpPost]
        public ActionResult HonorUpload()
        {
            try
            {
                Stream stream;
                string fileName;
                List<string> ImageUrls = new List<string>();
               
                for(var i=0;i<Request.Files.Count;i++)
                {
                    HttpPostedFileBase httpPostedFile = Request.Files[i];
                    if (httpPostedFile == null)
                        throw new ArgumentException("没有选择上传文件");
                    stream = httpPostedFile.InputStream;
                    fileName = Path.GetFileName(httpPostedFile.FileName);
                    var ext = (string.IsNullOrEmpty(fileName) || fileName.IndexOf('.') == -1)
                     ? ""
                     : fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();

                    var key = "xiang/" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(100, 999).ToString("") +
                              "." + ext;
                    var url = Comm.UploadToOss(key, stream);
                    ImageUrls.Add(url);                  
                }
                return Json(new { success = true, imageUrl = string.Join(",",ImageUrls) }, "text/plain");

            }
            catch (Exception ex)
            {
                return Json(new { success = false, error = ex.Message }, "text/plain");
            }
        }

参考文章:ajax图片上传

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值