springmvc多文件上传

springmvc多文件上传有不同的实现方式,个人使用过两种方式

1:使用MultipartFile[]进行文件对象接收,这种方式比较简单易记,代码奉上

@Controller("")
public class Upload{
     @RequestMapping("/up")
	public void up(@RequestParam("myfiles") MultipartFile[] myfiles , HttpServletRequest request){  //在定义接收参数时myfiles参数前必须加@requestParam注解
		boolean result = savePic(request, myfiles);
		if(result){
			System.out.println("上传成功!");
		}else{
			System.out.println("上传失败!");
		}
	}  

     //保存的方法等同于单文件上传的保存方式 public boolean savePic(HttpServletRequest request,MultipartFile[] multipartFile){ try { if(multipartFile!=null){ for (int i = 0; i < multipartFile.length; i++) { String filePath = request.getServletContext().getRealPath("upPic"); String fileName =new Date().getTime()+multipartFile[i].getOriginalFilename().substring(multipartFile[i].getOriginalFilename().indexOf("."), multipartFile[i].getOriginalFilename().length()); String newFileName = filePath+File.separator+fileName; File file = new File(newFileName); if(!file.getParentFile().exists()){ file.getParentFile().mkdir(); } multipartFile[i].transferTo(file); } return true; } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } }

2、第二种使用过的方式使用的是commonsMutipart组件上传

@Controller("")
public class upload{
      @RequestMapping("/up")
	public void up(@RequestParam("myfiles") CommonsMultipartFile[] myfiles , HttpServletRequest request){
		boolean result = savePic(request, myfiles);
		if(result){
			System.out.println("上传成功!");
		}else{
			System.out.println("上传失败!");
		}
	}  
   
        public boolean savePic(HttpServletRequest request,CommonsMultipartFile[] myfiles){
		try {
			if(myfiles!=null){
				for (int i = 0; i < myfiles.length; i++) {
					String filePath = request.getServletContext().getRealPath("upPic");
					String fileName =new Date().getTime()+myfiles[i].getOriginalFilename().substring(myfiles[i].getOriginalFilename().indexOf("."), myfiles[i].getOriginalFilename().length());
					FileOutputStream fos = new FileOutputStream(new File(filePath+File.separator+fileName));
					@SuppressWarnings("cast")
					InputStream is = (InputStream)myfiles[i].getInputStream();  //获取上传对象的输入流
					
					byte[] buffer = new byte[1024];
					@SuppressWarnings("unused")
					int flg = 0;
					//将上传对象的内容写入到新创建的输出流中
					while((flg = is.read(buffer, 0, buffer.length))!=-1){
						fos.write(buffer, 0, buffer.length);
					}
					//关闭输入输出流
					fos.close();
					is.close();
				}
				return true;
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return false;
	}  
}

  

 
posted @ 2016-09-05 20:34  西风恶  阅读(323)  评论(0编辑  收藏  举报