springmvc多图片上传

多图片上传

service层传递参数

// 文件夹名称
		String folder = "attachment";
		// 上传图片
		 Map<String, String> map = FileUtil.uploadManyFlie(request, folder);

FileUtil: 

public static Map<String,String> uploadManyFlie(HttpServletRequest request,String folder) throws Exception, Exception{
    	//创建一个数组
    Map<String,String> map=new HashMap<String,String>();
    	 //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            System.out.println(iter);
            while(iter.hasNext()){
            	System.out.println("++++");
                //记录上传过程起始时的时间,用来计算上传时间  
                int pre = (int) System.currentTimeMillis();  
                //取得上传文件  
                List<MultipartFile>files = multiRequest.getFiles(iter.next());
                if(files != null){  
                	for (MultipartFile file : files) {
	                    //取得当前上传文件的文件名称  
	                    String myFileName = file.getOriginalFilename();  
	                    //如果名称不为“”,说明该文件存在,否则说明该文件不存在  
	                    if(myFileName.trim() !=""){  
	                        System.out.println(myFileName);  
	                        //取得前缀
	                        String name=null;
	                        name = myFileName.substring(0,myFileName.indexOf("."));
	                        System.out.println(name);
	                        // 取得后缀
	                        String postfix = null;
	                        postfix = myFileName.substring(myFileName.indexOf(".")).toUpperCase();
	                        String fileName = null;
	                       String str=UUID.randomUUID().toString();
	                       
	                        //获取根目录
	                        String root = request.getSession().getServletContext()
	                                .getRealPath("/upload/" + folder)
	                                + "/";
	                        //重命名上传后的文件名  
	                         fileName = str+postfix;
	                        String savePath =root+fileName;
	                        System.out.println(savePath);
	                        File localFile = new File(savePath);  
	                        file.transferTo(localFile);  
	                       String imgurl= (request.getContextPath() + "/upload/attachment" + "/" + str)
	                                .replace("//", "/");
	                        map.put(name, imgurl+postfix);
	                    }
                    }  
                }  
                //记录上传该文件后的时间  
                int finaltime = (int) System.currentTimeMillis();  
                System.out.println(finaltime - pre);  
            }  
            
        } 
    	
    	return map;
    }

返回结果处理:

if (map == null) {
				return "1";
			}else{
				for (String  name : map.keySet()) {
					
					Attachment attachmently = new Attachment();
					attachmently.setAttachmentName(map.get(name));// 附件保存地址
					attachmently.setOriginalName(name);// 附件原始名称
					attachmently.setAttachmentType(type);// 1标图 2 小区者资料
					attachmently.setSort(Integer.parseInt(name));
					attachmently.setUploadTime(DateUtils
							.format(Constant.DEFAULT_TIME_FORMAT));

					if (type == 1) {// type的值为1时上传到小区表
						attachmently.setHomeCommunity(homeCommunity);
					} else if (type == 2) {
						attachmently.setHomeMessage(homeMessage);
					}else if (type == 3) {
						attachmently.setHomeMessage(homeMessage);
						attachmently.setRoom(room);
					}else if (type == 4) {
						attachmently.setArticle(article);
					}else if (type == 5) {
						attachmently.setHomeDistrict(homeDistrict);
					}else if (type == 6) {
						attachmently.setRoom(room);
					/*}else if (type == 7) {
						attachmently.setHomeMessage(homeMessage);*/
					}else if (type == 8) {
						attachmently.setHomeMessage(homeMessage);}
					// 保存附件
					 dao.save(attachmently);
				}
				return "2";
			}
			

Controller层:

@RequestMapping(value = { "uploadAttchmentMany", "/" })
    public void addUser(@ModelAttribute(value = "Attachment") Attachment attachmentt,HttpServletRequest request,HttpServletResponse response) throws Exception, Exception{  
    	  JSONObject json = new JSONObject();
          PrintWriter out =response.getWriter();
        try {
			String result=attachmentService.uploadhelpAttchmentmany(attachmentt.getHomeCommunity(), attachmentt.getHomeMessage(),attachmentt.getRoom(),attachmentt.getArticle(),attachmentt.getHomeDistrict(), attachmentt.getAttachmentType(), request);
			   if(result.equals("1")){
				   DwzResponseUtil.setJson(json, Constant.HTTP_STATUSCODE_ERROR, "请选择图片文件", "main59",  "closeCurrent");
			   }else{
				   DwzResponseUtil.setJson(json, Constant.HTTP_STATUSCODE_SUCCESS, "上传成功", "main59", "closeCurrent");
			   }
			   out.print(json);
		} catch (Exception e) {
			 DwzResponseUtil.setJson(json, Constant.HTTP_STATUSCODE_ERROR, "更新失败", "main59", "closeCurrent");
	            out.print(json);
		}
     
         
    }

xml配置

<!-- 上传文件大小、缓存、编码 配置 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<property name="maxUploadSize" value="10485760000" />
		<property name="maxInMemorySize" value="40960" />
	</bean>

 

转载于:https://my.oschina.net/u/3116648/blog/897635

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值