html页面选择多张图片一起提交上传 完整版html5+css+jQuery 附前后端代码

5 篇文章 0 订阅

html页面选择多张图片一起提交上传 附代码

 

Java后端代码----------------------- 

   
    Java后端代码

    @ResponseBody
    @RequestMapping(value = "/uploadImg")
    public String uploadImg(HttpServletRequest request, @RequestParam String toJson,
                            @RequestParam(value = "fileBlob", required = false) MultipartFile[] fileBlob) {

        try {
            System.err.println("json参数" + toJson.toString());
            System.err.println("文件数量" + fileBlob.length);
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            StringBuilder stringBuilder = new StringBuilder();
            
            if (fileBlob.length > 0) {
                String realPath = request.getSession().getServletContext().getRealPath("/") + "imgFile/";
                ;//获取服务器路径
                for (MultipartFile multipartFiles : fileBlob) {
                    if (!multipartFiles.isEmpty()) {
                        String nowTime = sd.format(new Date());
                        String fileType = multipartFiles.getContentType().split("/")[1];//文件后缀

                        if (!multipartFiles.isEmpty()) {
                            try {
                                File filepath = new File(realPath);
                                if (!filepath.exists())
                                    filepath.mkdirs();
                                // 文件保存路径
                                String filePath = realPath + nowTime + "." + fileType;
                                multipartFiles.transferTo(new File(filePath));
                                stringBuilder.append(filePath).append(",");///文件路径
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                    }

                }

            }

            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

html5 + js 代码----------

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>

</head>
<body>
<div>

    <div id="imgList">
    </div>

    <div style="display: none">
        <input type="file" id="toFileId" onchange="onchangeFile(this)" accept="image/*">
    </div>

    <div onclick="onclickFile()" style='  float: left;width: 150px;height: 150px;
                             margin-left: 10px;background-color: cornsilk; text-align: center; font-size: 80px; line-height: 150px;'>
        +
    </div>


    <button style="width:100%; height: 4rem; border: aqua 2px solid; background-color: red; font-size: 2rem;"
            onclick="buttonImg()">提交
    </button>

    <div id="filePathDiv" style='width: 100%;height: auto;
    word-wrap: break-word;word-break: break-all;overflow: hidden;
                           background-color: cornflowerblue;'></div>


</div>


<script type="text/javascript">

    var imgArr = [];//图片数组
    var imgArrType = [];//图片类型数组


    /**
     * 唤起选择文件控件
     */
    function onclickFile() {
        document.getElementById('toFileId').click();
    }


    /**
     * 选择图片后 回调文件处理
     * @param files
     */
    function onchangeFile(files) {

        var file = files.files[0];
        var fileType = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length);//获取文件后缀

        var base64Img = "";
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            base64Img = reader.result; //获取到图片的base64编码
            imgArr.push(base64Img);//放入数组
            imgArrType.push(fileType);
            toImgList();//刷新数组 展示到页面
            document.getElementById('toFileId').value = "";//清掉刚选择的图片信息 不然不能连续选两张同样的文件
        };

    }


    /**
     * 加载图片列表
     */
    function toImgList() {
        //删除图标
        var ico = "<svg class=\"icon\" style=\"width: 1.5em; height: 1.5em;vertical-align: middle;fill: currentColor;overflow: hidden;\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"1612\" data-spm-anchor-id=\"a313x.7781069.1998910419.i3\"><path d=\"M512 0C227.84 0 0 227.84 0 512s227.84 512 512 512c284.096 0 512-227.84 512-512S796.096 0 512 0L512 0zM768 696.32 696.256 768 512 583.68 327.616 768 256 696.32 440.256 512 256 327.68 327.616 256 512 440.32 696.256 256 768 327.68 583.616 512 768 696.32 768 696.32zM768 696.32\" p-id=\"1613\"></path></svg>";

        var textHtml = "";
        for (var i = 0; i < imgArr.length; i++) {
            textHtml += " <div style='    float: left;width: 150px;height: 150px; margin-left: 10px;position: relative;'> " +
                "<img  style='width: 100%; height: auto' src=" + imgArr[i] + ">" +
                "<a onclick='deleteImg(" + i + ")' style='top:5px;right:5px;display:block; position:absolute;'>" + ico + "</a>" +
                "</div>";
        }
        $("#imgList").html(textHtml);
    }


    /**
     * 根据索引删除图片
     * @param i
     */
    function deleteImg(i) {
        imgArr.splice(i, 1);
        imgArrType.splice(i, 1);
        toImgList();
    }


    /**
     * 第三步上传图片 提交
     */

    function buttonImg() {

        var jsonObject = {};
        jsonObject.id = 1;
        jsonObject.name = "name";
        var toJson = JSON.stringify(jsonObject);

        var formdata = new FormData();
        formdata.append('toJson', toJson);

        for (var i = 0; i < imgArr.length; i++) {
            var fileBlob = baseToFile(imgArr[i], imgArrType[i]);
            formdata.append('fileBlob', fileBlob);
        }

        $.ajax({
            url: "/uploadImg", //请求地址
            data: formdata, //参数
            type: "POST",
            dataType: "text", //返回格式
            processData: false,
            contentType: false,
            cache: false,
            success: function (data) {
                $("#filePathDiv").html(data);

            },
            error: function (e) {
            }
        });
    }


    /**
     base64编码转file对象
     */
    function baseToFile(base, type) {
        var img = base.split(',')[1];
        img = window.atob(img);
        var ia = new Uint8Array(img.length);
        for (var j = 0; j < img.length; j++) {
            ia[j] = img.charCodeAt(j);
        }
        ;
        var blob = new Blob([ia], {type: "image/" + type});
        return blob;
    }

</script>
</body>
</html>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦唉m

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值