页面:
spring 配置
出去mvc基本配置外,添加
CommonsMultipartResolver继承自spring的CommonsFileUploadSupport,后者需要apache
commmon io和fileupload包的依赖。可以选择配置maxUploadSize属性,单位byte
controller
<form action="upload" method="post" enctype="multipart/form-data" >
文件:<input type="file" name="file"/>
<input type="submit" />
</form>
spring 配置
出去mvc基本配置外,添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
CommonsMultipartResolver继承自spring的CommonsFileUploadSupport,后者需要apache
commmon io和fileupload包的依赖。可以选择配置maxUploadSize属性,单位byte
controller
@Controller
@RequestMapping("/upload")
public class UploadConroller extends BaseController {
@RequestMapping(method=RequestMethod.GET)
public String upload(){
return "upload";
}
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request){
if(!file.isEmpty()){
try {
String basePath = request.getSession().getServletContext().getRealPath("/");
String ofName = file.getOriginalFilename();
ofName = ofName.substring(ofName.lastIndexOf("."));
OutputStream out = new FileOutputStream(
new File(basePath+"/WEB-INF/upload/"
+new Random().nextInt(1000)+ofName));
out.write(file.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return "SUCC";
}
}