springMVC上传图片

一、需要导入springmvc文件上传的jar包,否则会出现异常java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory

二、创建上传页面form表单

1 <form action="upload/uploadPic.do" method="post" enctype="multipart/form-data">
2         <input type="file" name="pic">
3         <br>
4         <input type="submit" value="submit">
5     </form>

三、在springMVC配置文件中设置文件上传配置

1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2         <!-- 以字节为单位  -->
3         <property name="maxUploadSize" value="1024000"></property>
4     </bean>

四、controller类的编写

 1 //跳转到表单页
 2     @RequestMapping("/toForm.do")
 3     public String toForm(){
 4         return "form1";
 5     }
 6     
 7     //文件上传
 8     @RequestMapping("/uploadPic.do")
 9     public String uploadPic(HttpServletRequest req) throws IOException{
10         MultipartHttpServletRequest mr = (MultipartHttpServletRequest) req;
11         //获得文件
12         MultipartFile file = mr.getFile("pic");
13         //获得文件字节数组
14         byte[] bs = file.getBytes();
15         //根据时间及随机数创建文件名
16         String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
17         Random random = new Random();
18         for(int i = 0;i < 3;i++){
19             fileName = fileName + random.nextInt(10);
20         }
21         //获得文件的原始文件名
22         String originalFilename = file.getOriginalFilename();
23         //对原始文件名切割获得后缀名
24         String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
25         //获得项目路径
26         String realPath = req.getSession().getServletContext().getRealPath("/");
27         //创建字节输出流
28         OutputStream out = new FileOutputStream(new File(realPath + "/upload/" + fileName + suffix));
29         out.write(bs);
30         out.flush();
31         out.close();
32         return "success";
33     }

 

posted @ 2018-04-24 09:48  cat_fish  阅读(188)  评论(0编辑  收藏  举报