1.controller
@RequestMapping("/toUpload.do")
public String toUpload() {
//---跳转到upload.jsp
return "upload";
}
@RequestMapping("/upload.do")
public String upload(HttpServletRequest request) throws IOException {
//转换request
MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request;
//获得文件
MultipartFile file=mr.getFile("pic");
//获得文件的字节数组
byte[] by=file.getBytes();
String fileName=new SimpleDateFormat("yyyyMMdd").format(new Date());
Random r1=new Random();
for (int i = 0; i < 3; i++) {
fileName=fileName+r1.nextInt(10);
}
//获得文件的原始文件名,后缀,项目部署路径
String orgname=file.getOriginalFilename();
String suffix=orgname.substring(orgname.lastIndexOf("."));
String real=request.getSession().getServletContext().getRealPath("/");
//组装文件的全路径
String picname=real+"\\upload\\"+fileName+suffix;
//定义输出流
OutputStream out=new FileOutputStream(picname);
out.write(by);
out.flush();
return "success";
}
2.upload.jsp
<body>
<form action="test/upload.do" method="post" enctype="multipart/form-data">
文件: <input type="file" name="pic"><br/>
<input type="submit" value="click">
</form>
</body>
3.视图解析器应为
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"></property>
<property name="maxInMemorySize" value="4096"></property>
</bean>
注意:
1.
method=“post”
enctype=“multipart/form-data” //容易拼写错误
2.
id=“multipartResolver”
bean的属性id和class都必须存在且id必须为multipartResolver