如何在前端用js进行多图片上传

如题所述

第1个回答  2022-06-05
    产品提了一个需求,要求在一个html中实现多行多图片上传,原型图如下:

    2.1 :html

        html页面由前端实现,此处增加<ul><li></li></ul>是为了配合图片单击放大图片功能的实现

        <ul  id="ul_other">

              <li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>

        </ul>

    2.2 :js

        var imgSrc_other=[];

        var imgFile_other=[];

        function add_file_image(id) {

            var fileList =document.getElementById("file_"+id).files;// js 获取文件对象

            if (verificationFile(fileList[0])){

                for(var i =0;i

                    var imgSrcI =getObjectURL(fileList[i]);

                        if (id=="other"){

                            imgSrc_other.push(imgSrcI);

                            if(fileList[i].size/1024 >100) { //大于100kb,进行压缩上传

                                 fileResizetoFile(fileList[i],0.6,function(res){

                                  imgFile_other.push(res);

                                })

                            }else{

                                imgFile_other.push(res);

                        }

                    }

                    addNewContent(id);

                }

        }

    //新增图片

    function addNewContent(obj) {

        //删除原先

        $("#ul_"+obj).html("");

        //判断循环新增

        var  text="";

        if (obj=="other"){

           for(var a =0;a < imgSrc_examReportCard.length;a++) {

            text +='<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>';

           }

        }else{

            console.log('脏数据');

        }

        var oldBox ="<li><div class=\"filediv\"><span>+</span>\n" +

        "<input type=\"file\" id=\"file_"+obj+"\"  class=\"file_input\" onchange=\"add_file_image('"+obj+"')\">\n" +

        "</div></li>";

        $("#ul_"+obj).html( text+localText);

    }

    使用formData上传

    var form =document.getElementById("form_addArchive");//表单id

    var formData =new FormData(form);

    $.each(imgFile_other,function(i, file){

        formData.append('imgFileOther', file);

    });

$.ajax({

    url:url,

    type:'POST',

    async:true,

    cache:false,

    contentType:false,

    processData:false,

    dataType:'json',

    data:formData,

    xhrFields:{

        withCredentials:true

    },

    success:function(data) {

     }

  },

  error:function(XMLHttpRequest, textStatus, errorThrown) {

    }

})

后台使用@RequestParam(value ="imgFileOther", required=false) List<MultipartFile> imgFileOther, 接受

//获取图片url以便显示       

//文件格式验证

//图片压缩