使用Spring MVC实现上传功能,在项目开发中也是经常使用到的。例如在使用Spring MVC时,上传和Struts也有大部分相似的处理。
如图1所示,首先引入上传相关罐
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar
2,编写前台JSP代码
- <BODY>
- <form action = “test / upload.do” method = “post” enctype = “multipart / form-data” >
- 图:<input type = “file” name = “pic” > <br>
- <input type = “submit” value = “submit” > <br>
- </ FORM>
- </ BODY>
3,后台上传代码
- @RequestMapping (value = “/upload.do” )
- public String upload(Person person,HttpServletRequest request) throws Exception {
-
- MultipartHttpServletRequest rm =(MultipartHttpServletRequest)请求;
-
- CommonsMultipartFile cfile =(CommonsMultipartFile)rm.getFile(“pic” );
-
- byte [] bfile = cfile.getBytes();
- String fileName = “”;
-
- SimpleDateFormat format = new SimpleDateFormat(“yyyyMMddHHmmssSSS”);
- fileName = format.format(new Date());
-
- 随机随机= 新 随机();
- for(int i = 0; i < 3; i ++){
- fileName = fileName + random.nextInt(9);
- }
-
- String origFileName = cfile.getOriginalFilename();
-
- 字符串后缀= origFileName.substring(origFileName.lastIndexOf(“。”));
-
- String path = request.getSession()。getServletContext()。getRealPath(“/” );
-
- OutputStream out = new FileOutputStream(new File(path + “/ upload /” + fileName + suffix));
- out.write(BFILE);
- 了了out.flush();
- out.close();
- 返回“/ index” ;
- }