今天来个新的需求:将之前的单图片上传改为多文件上传。

例图:jsp 多图片上传

此需求提出就需要将之前的存储方式做下改变,由图片id变为图片id1,图片id2,...  。在存储图片时需要将没一个图片进行保存。例:

主表保存方式:jsp 多图片上传

图片表保存方式:

jsp 多图片上传

下面看一下jsp页面与js方法

jsp 多图片上传

代码:

<td align="right">
                        <label class="Validform_label">
                            合同图片:
                        </label>
                    </td>
                    <td class="value" style="height:40px;">
                        <span class="Validform_checktip"></span>
                        <div class="col-xs-10">
                        <input type="hidden" id="fileid"  name="fileid" value=""/>
                                    <label style="border: 1px dashed #dbdadd;padding: 6px;background-color: #80808033;">
                                       <input style="position:absolute;opacity: 0;width: 135px;height: 35px;left: 5px;" id="choose-file" multiple type="file" name="file" accept="image/gif,image/jpeg,image/x-png,image/png" />
                                                                                                                                                             选择图片
                                    </label>
                                    <!--图片预览列表-->
                                    <div class="file-list" style="display: inline-block;width: auto;position: relative;top: 7px;">
                                    </div>
                        </div>    
                    </td>
                    <td align="right">
                        <label class="Validform_label">
                            工作许可证图片:
                        </label>
</td>

 

JS方法:


     /*
     * 保存
     */
    function doSave(file){
            //使用formData发送ajax请求,注意[0],发现很多博客都没有写
            var formData = new FormData($("#formobj")[0]);
            //删除formData中的File对象,设置将我们需要上传的fileList中File对象
            formData.delete("files");
            formData.append("files",file);
            //添加需要删除的已上传的图片的id,后台解析删除
            //formData.append("removeList",removeList);
            
            $.ajax({
                url : "teacherController.do?uploadd",
                data : formData,
                type : "post",
                dataType : "json",
                cache : false,//上传文件无需缓存
                processData : false,//用于对data参数进行序列化处理 这里必须false
                contentType : false, //必须
                success : function (resp) {
                    if(resp.success){
                        fileId = resp.attributes.fileid;
                        alert("保存成功");
                        reviewFile(file,fileId)
                        var tid=$("#fileid").val();
                        if(tid == '' || tid ==null || tid =='undefind'){
                        $("#fileid").val(fileId);
                        }else{
                            tid = tid+","+fileId;
                            $("#fileid").val(tid);
                        }
                    }else{
                        alert("保存失败");
                    }
                }
            });
            }
    
    
    //回显图片
    function reviewFile(file,fileId){
        //实例化fileReader,
        var fd = new FileReader();
        //获取当前选择文件的类型
        var fileType = file.type;
        //调它的readAsDataURL并把原生File对象传给它,
        fd.readAsDataURL(file);//base64
        //监听它的onload事件,load完读取的结果就在它的result属性里了
        fd.onload = function(){
            $list.append('<label class="file-item" data-id="'+fileId+'" style="top:7px;"><img src="'+this.result+'" alt="" style="width: 55px;height: 55px;" /><i class="file-del" style="position: relative;left:-15px;top: -20px;color: red;">&times;</i></label>');
        }
        
    }
  

    $(function () {
        /**
         * 编辑页面,获取已上传的图片,根据自己的需求更改
         * */
         var deviceId = "${param.deviceId}";
        if (deviceId) {
            var url = "teacherController.do?uploadd";
            $.post(url,{deviceId:deviceId},function (data) {
                for (var i=0;i<data.length;i++) {
                    //attachmentId是已上传图片的id,一般图片存储在服务器端规定的某个文件夹,可以使用nginx代理来回显
                    $list.append('<label data-id="'+data[i].attachmentId+'"><img  alt="" style="width: 55px;height: 55px;" /><i class="file-del" style="position: relative;left:-15px;top: -20px;color: red;">&times;</i></label>')
                }
            });
        } 
    });


    /*
    * 图片上传
    * */
    //选择文件按钮
    $file = $("#choose-file");
    //回显的列表
    $list = $('.file-list');
    //选择要上传的所有文件
    fileList = [];
    //已添加需要删除的文件
    removeList = "";
    //当前选择上传的文件
    var curFile;
    //当前选择上传的文件id
    var fileId;
    $file.on('change',function(){
        curFile = this.files;
        for(var i=0,len = curFile.length;i < len;i++){
            doSave(curFile[i]);
        }
    });
    
  
    //删除图片
    $(".file-list").on('click','.file-del',function(){
        var $parent = $(this).parent();
        var index = $parent.index(".file-item");
        //index==-1时表示是已上传回显的图片
        if (index != -1) {
            removeList += $parent.attr("data-id")+",";
        }
        var fid=$("#fileid").val();
        var filid="";
        var aa = new Array();
        aa= removeList.split(",");
        for(var u =0;u<aa.length;u++){
            if(aa[u]!='' && aa[u] != null){
                filid=fid.replaceAll(aa[u], "");
            }
        }
        $("#fileid").val("");
        $("#fileid").val(filid);
        //删除选择的图片
        fileList.splice(index,1);
        $parent.remove();
    });
    
    JAVA 代码 文件上传

    
    /**
     * 文件上传
     * 
     * @param Filedata
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(params = "uploadd")
    @ResponseBody
    public AjaxJson uploadFile(HttpServletRequest request,@RequestParam( value="files",required=false)MultipartFile multipartFile) throws IllegalStateException, IOException {
        AjaxJson j = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUser();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String, Object> map = new HashMap<String, Object>(); // 回传参数集合
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file =  entity.getValue();// 获取上传文件对象
            String fileName = file.getOriginalFilename();
            String extend = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            try {
            TSAttachment att = new TSAttachment();
            att.setAttachmenttitle(fileName);
            Timestamp ts = new Timestamp(new Date().getTime());
            att.setCreatedate(ts);
            att.setTSUser(user);
            att.setExtend(extend);
            att.setAttachmentcontent(multipartFile.getBytes());
            systemService.save(att);
            j.setSuccess(true);
            map.put("fileid", att.getId());
            map.put("filename", att.getAttachmenttitle());
            /*map.put("realfilename", fileName);
            map.put("attachmentId", att.getId());*/
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        j.setAttributes(map);
        return j;
    }
    

save方法按自己的需求编写就可以了。

这里JS有些部分也需要按自己的需求编写,这是添加页面的具体代码。在修改页面首先需要回显添加的图片,仍可以对图片进行(添加、删除、回显)操作。

JS代码如下:

 /*
     * 保存
     */
    function doSave(file){
            //使用formData发送ajax请求,注意[0],发现很多博客都没有写
           var formData = new FormData($("#formobj")[0]);
           //删除formData中的File对象,设置将我们需要上传的fileList中File对象
           formData.delete("files");
           formData.append("files",file);
            //添加需要删除的已上传的图片的id,后台解析删除
           //formData.append("removeList",removeList);
            
           $.ajax({
               url : "teacherController.do?uploadd",
               data : formData,
               type : "post",
               dataType : "json",
               cache : false,//上传文件无需缓存
               processData : false,//用于对data参数进行序列化处理 这里必须false
               contentType : false, //必须
               success : function (resp) {
                   if(resp.success){
                       fileId = resp.attributes.fileid;
                       alert("保存成功");
                       reviewFile(file,fileId)
                       var tid=$("#fileid").val();
                       if(tid == '' || tid ==null || tid =='undefind'){
                       $("#fileid").val(fileId);
                       }else{
                           tid = tid+","+fileId;
                           $("#fileid").val(tid);
                       }
                   }else{
                       alert("保存失败");
                   }
               }
           });
           
   }
   
   
    //回显图片
   function reviewFile(file,fileId){
       //实例化fileReader,
       var fd = new FileReader();
       //获取当前选择文件的类型
       var fileType = file.type;
       //调它的readAsDataURL并把原生File对象传给它,
       fd.readAsDataURL(file);//base64
       //监听它的onload事件,load完读取的结果就在它的result属性里了
       fd.onload = function(){
           //
           $list.append('<label class="file-item" data-id="'+fileId+'" style="top:7px;"><img src="'+this.result+'" alt="" style="width: 55px;height: 55px;" /><i class="file-del" style="position: relative;left:-15px;top: -20px;color: red;">&times;</i></label>');
       }
       
   }
 

   $(function () {
       /**
        * 编辑页面,获取已上传的图片,根据自己的需求更改
        * */
       var htmly="";
       var htmlyG="";
       var deviceId = $("#fileid").val();//合同照片
       var deviceIdG = $("#fileid2").val();//工作证照片
       if (deviceId) {
           var url = "teacherController.do?getpic";
           $.ajax({
               url : url,
               data : {
                   "deviceId":deviceId
               },
               type : "post",
               dataType : "json",
               success : function (resp) {
                   if(resp.success){
                       var xhProvinceDatas=resp.obj;
                       $.each(xhProvinceDatas,function(index,item){
                              htmly+='<label class="file-item" data-id="'+item.aid+'" style="top:7px;"><img src="teacherController.do?showImg&id='+item.aid+'" alt="" style="width: 55px;height: 55px;" /><i class="file-del" style="position: relative;left:-15px;top: -20px;color: red;">&times;</i></label>';
                       });
                       $('.file-list').append(htmly);
                   }else{
                       alert("保存失败");
                   }
               }
           });
       }
   });


   /*
   * 图片上传
   * */
   //选择文件按钮
   $file = $("#choose-file");
   //回显的列表
   $list = $('.file-list');
   //选择要上传的所有文件
   fileList = [];
   //已添加需要删除的文件
   removeList = "";
   //当前选择上传的文件
   var curFile;
   //当前选择上传的文件id
   var fileId;
   $file.on('change',function(){
       curFile = this.files;
       for(var i=0,len = curFile.length;i < len;i++){
           doSave(curFile[i]);
       }
   });
   
 
    //删除图片
   $(".file-list").on('click','.file-del',function(){
       var $parent = $(this).parent();
        var index = $parent.index(".file-item");
        //index==-1时表示是已上传回显的图片
        if (index != -1) {
            removeList += $parent.attr("data-id")+",";
        }
        var fid=$("#fileid").val();
        var filid="";
        var aa = new Array();
        aa= removeList.split(",");
        for(var u =0;u<aa.length;u++){
            if(aa[u]!='' && aa[u] != null){
                filid=fid.replaceAll(aa[u], "");
            }
        }
        $("#fileid").val("");
        $("#fileid").val(filid);
        //删除选择的图片
        fileList.splice(index,1);
        $parent.remove();
   });
    

唯一不同在于进入页面的加载方法。

JAVA后端代码:

    /**
     * 教师合同照片获取
     * 
     * @param ids
     * @return
     */
    @RequestMapping(params = "getpic")
    @ResponseBody
    public AjaxJson getpic(HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
            message = "获取图片成功";
            String deviceId=request.getParameter("deviceId");
            List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
            try {
                if(StringUtil.isNotEmpty(deviceId)){
                    if(deviceId.indexOf(",")>-1){
                        for (String id : deviceId.split(",")) {
                            if(StringUtil.isNotEmpty(id)){
                                Map<String,Object> map=new HashMap<String,Object>();
                                TSAttachment t = teacherService.getEntity(TSAttachment.class, id);
//                                    list.add(t);
                                map.put("aid", t.getId());
                                map.put("title", t.getAttachmenttitle());
                                map.put("attmo", t.getAttachmentcontent());
                                map.put("exd", t.getExtend());
                                list.add(map);
                            }
                        }
                    }else{
                        Map<String,Object> map=new HashMap<String,Object>();
                        TSAttachment t = teacherService.getEntity(TSAttachment.class, deviceId);
//                        list.add(t);
                        map.put("aid", t.getId());
                        map.put("title", t.getAttachmenttitle());
                        map.put("attmo", t.getAttachmentcontent());
                        map.put("exd", t.getExtend());
                        list.add(map);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                message = "获取图片失败";
            }
        j.setObj(list);
        j.setMsg(message);
        return j;
    }

说的有点多,希望能帮到大家,有不清楚的地方请留言。

 

相关文章: