【Java】SpringMVC实现多张图片上传实例

实现在Springmvc中上传图片功能很好实现。需求是将多张或单张图片上传至某个文件夹下,同时保存在数据库中和服务器上。现在我将会展现完整例子。

1、前提:在pom中添加相关的jar包。

[html]  view plain  copy
  1. <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->  
  2. <dependency>  
  3.     <groupId>commons-fileupload</groupId>  
  4.     <artifactId>commons-fileupload</artifactId>  
  5.     <version>1.3.2</version>  
  6. </dependency>  
2、 SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file。在applicationContext-mvc.xml中添加如下代码:


代码:

[html]  view plain  copy
  1. <bean id="multipartResolver"      
  2.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      
  3.         <!-- set the max upload size10MB -->      
  4.         <property name="maxUploadSize">      
  5.             <value>10485760</value>      
  6.         </property>      
  7.         <property name="maxInMemorySize">      
  8.             <value>4096</value>      
  9.         </property>     
  10.         <property name="defaultEncoding">    
  11.             <value>utf-8</value>    
  12.         </property>    
  13.     </bean>   

3.  在上传按钮时js代码:

[javascript]  view plain  copy
  1. /** 
  2.  * 点击添加图片 
  3.  * 上传 多张图片 
  4.  * 原生写法 
  5.  * @param im 
  6.  * @returns 
  7.  */  
  8.   
  9. function uploadimgforlist(im){  
  10.     var fileTid = $(".ant-checkbox-checked[name=imgsubcheckbox]").children().eq(0).val();//获取文件夹的id  
  11.     if(typeof(fileTid) != "undefined"){  
  12.         var path = imgpathchange(im);  
  13.         var file_name = $("input[name='fileImg']");  
  14.         var addimg='<li>'  
  15.                         +'<div class="uploadimg position-rv" οnmοuseοver="showBtnImg(this)" οnmοuseοut="hideBtnImg(this)">'  
  16.                             +'<form id="formId" enctype="multipart/form-data" method="post">'//action="../../file/toUpLoadBacthHmImage.do?tid='+fileTid+'"   
  17.                             +'</form>'  
  18.                            /*+    '<img  src="'+path+'">' 
  19.                             +    '<div id="" class="position-ab imghandle dpnone">' 
  20.                             +       '<i class="iconfont icon-download" οnclick="downloadThisImage(this);"></i>' 
  21.                             +      '<i class="iconfont icon-delete pull-right deleteimgsigle" οnclick="deleteimgsigle(this)"></i>' 
  22.                             +   '</div>'*/  
  23.                         +'</div>'  
  24.                      +'</li>';  
  25.         $("#imgshowlist").append(addimg);  
  26.         $("#formId").append(file_name);  
  27.         var options = {  
  28.             url: '../../file/toUpLoadBacthHmImage.do',  
  29.             type: "post",  
  30.             dataType: 'json',  
  31.             data:{tid:fileTid},  
  32.             success:function(data){  
  33.                 if(data.result == true){  
  34.                     alert("上传成功");  
  35.                     location.reload();  
  36.                 }else {  
  37.                     alert("上传失败");  
  38.                 }  
  39.                    
  40.            },  
  41.            error:function(data,msg){  
  42.                 $.error("上传信息失败" + msg);  
  43.             }  
  44.        }  
  45.       $("#formId").ajaxSubmit(options);  
  46.     }else {  
  47.         alert("请先选择文件夹,在进行添加图片!");  
  48.     }  
  49.   
  50.   
  51. }  
4、 实现上传功能的Controller类方法:

[java]  view plain  copy
  1. /** 
  2.      * 多张图片上传(含单张) 
  3.      * @param request 
  4.      * @param response 
  5.      * @param model 
  6.      * @return 
  7.      * @author zhangsq 
  8.      */  
  9.     @RequestMapping("/toUpLoadBacthHmImage.do")  
  10.     public @ResponseBody Map<String, Object> toUpLoadBacthHmImage(HttpServletRequest request,   
  11.             HttpServletResponse response,ModelMap model,String tid,  
  12.             @RequestParam("fileImg") MultipartFile[] multipartfiles)   
  13.                     throws IllegalStateException, IOException{  
  14.         Map<String, Object> map = new HashMap<String, Object>();   
  15.         HmFile fileBean = hmFileService.findByTidFilesInfo(tid);  
  16.          /** 得到图片保存目录的真实路径 **/  
  17.         String realpath = properties.getProperty("file.acpath.server");  
  18.         /** 构建图片保存的目录 **/  
  19.         String filedir =File.separator  
  20.                 + SpellUtil.getFirstSpell(fileBean.getFileName());  
  21.         String filelocationdir = realpath + filedir;  
  22.         /** 根据真实路径创建目录 **/  
  23.         File logoSaveFile = new File(filelocationdir);  
  24.         if (!logoSaveFile.exists()){  
  25.             logoSaveFile.mkdirs();  
  26.         }  
  27.          boolean doFlag;  
  28.         if(null != multipartfiles && multipartfiles.length > 0){    
  29.             //MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;    
  30.             //List<MultipartFile> iter = multiRequest.getFiles("file");  
  31.             try {  
  32.                 for(MultipartFile picFile : multipartfiles){    
  33.                 //MultipartFile picFile = multiRequest.getFile(iter.next());    
  34.                 if(null != picFile && null != picFile.getOriginalFilename()  
  35.                         && !"".equals(picFile.getOriginalFilename().trim())  
  36.                         && !"null".equals(picFile.getOriginalFilename().trim())){  
  37.                       
  38.                     synchronized(HmFileImageController.this){  
  39.                         String imagename = new SimpleDateFormat("yyyyMMddHHmmss")  
  40.                                 .format(new Date()).concat(picFile.getOriginalFilename());  
  41.                         String filename = filelocationdir + File.separator +imagename;  
  42.                         File file = new File(filename);  
  43.                           
  44.                         picFile.transferTo(file);//上传至服务器  
  45.                         //将文件图片插入数据库  
  46.                         HmImage imgBean = new HmImage();  
  47.                         imgBean.setTid(UUIDUtil.getUUID());  
  48.                         imgBean.setHid(tid);  
  49.                           
  50.                         long curTimeStamp = System.currentTimeMillis();  
  51.                         String fileACPath = properties.getProperty("file.acpath.views.server");   
  52.                         String spell = SpellUtil.getFirstSpell(fileBean.getFileName());  
  53.                         fileACPath=String.format(fileACPath,spell,imagename,curTimeStamp);  
  54.                           
  55.                         imgBean.setFilePath(fileACPath);  
  56.                         //imgBean.setFilePath(fileACPath.replaceAll("/", "\\\\"));  
  57.                         String tid_insert = hmImagesService.insertSelective(imgBean);//保存在数据库中  
  58.                         hmFileService.updateByTidUpdateTimes(tid);//更新文件夹的时间  
  59.                         map.put("tid_insert", tid_insert);  
  60.                           
  61.                     }  
  62.                 }  
  63.             }  
  64.                 doFlag = true;  
  65.             } catch (IllegalStateException e) {  
  66.                 e.printStackTrace();  
  67.                 doFlag = false;  
  68.             } catch (IOException e) {  
  69.                 e.printStackTrace();  
  70.                 doFlag = false;  
  71.             }  
  72.             //遍历并保存文件    
  73.             map.put("result", doFlag);  
  74.         }    
  75.         return map;  
  76.   
  77.     }  
tid:是某个文件夹的id。该功能实现了多张图片上传,一是可以将图片保存在数据库(存储图片的路径),二是将图片存储在服务器上。

附上配置文路径文件:

[html]  view plain  copy
  1. file.acpath.server=/home/weihu/img_resource/school_web    <---- 服务器路径  
  2. file.acpath.views.server=http://www.zxctinfo.com:8080/school_web_img/%s/%s?t=%s      <---- 数据库路径  

你也可以自定义该路径的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值