07-springMVC笔记-file-upload文件上传
在项目中使用文件上传
1.导入包
commons-fileupload
commons-fileupload
1.4
2.写入配置文件
3.前端表单
4.写入核心代码
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getSession().getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:" + realPath);
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
return "上传成功";
}