使用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();
- //XXX.jpg
- 字符串后缀= 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” ;
- }