1.传统方式上传
@Controller
@RequestMapping("/fileupload")
public class FileUpLoadControl {
@RequestMapping("/traditional")
public String traditional(HttpServletRequest request) throws Exception {
System.out.println("传统的文件上传方式....");
String realPath = request.getSession().getServletContext().getRealPath("/fileupload/");
System.out.println("realPath = " + realPath);
File file = new File(realPath);
if(!file.exists()){
file.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem f:fileItems){
if(!f.isFormField()){
String filename = UUID.randomUUID().toString().replaceAll("-","")+"-"+f.getName();
File sonfile = new File(realPath,filename);
System.out.println(sonfile.getName());
f.write(sonfile);
}
}
return "success";
}
2.SpringMVC方式上传
@RequestMapping("/modern")
public String modern(HttpServletRequest request,MultipartFile file) throws IOException {
System.out.println("modern的文件上传方式....");
String realPath = request.getSession().getServletContext().getRealPath("/fileupload/");
System.out.println("realPath = " + realPath);
File files = new File(realPath);
if(!files.exists()){
files.mkdirs();
}
System.out.println(file.getOriginalFilename());
String filename = UUID.randomUUID().toString().replaceAll("-","")+"_"+file.getOriginalFilename();
System.out.println("filename = " + filename);
file.transferTo(new File(realPath,filename));
return "success";
}
}
3.前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="fileupload/traditional" method="post" enctype="multipart/form-data">
请选择上传的文件<input type="file" name="file"><br>
点击这里进行提交<input type="submit">
</form>
<form action="fileupload/modern" method="post" enctype="multipart/form-data">
请选择上传的文件<input type="file" name="file"><br>
点击这里进行提交<input type="submit">
</form>
</body>
</html>
注意要点:
1.SpringMVC编写文件上传更加简单,但需要在配置文件中配置文件解析器
2.在文件上传时,通过request.getSession.getServletcontext.getRealPath拿到相对于项目的绝对路径,然后进行文件的保存
3.在File中可以指定父目录和子目录进行创建文件