1.使用SpringBoot自带的MutilepartFile
2.代码如下:
前端:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h3>文件上传</h3>
<form th:action="@{/upload/document}" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
后端Controller层:
@RequestParam(“file”) 表明file应该跟前端的name相同.
file.transferTo(realPath)一定要用try-catch包起来,不然传入到对应的文件夹中,否则只会传输到最前的父文件夹下.
@RequestMapping("/document")
@ResponseBody
public void uploadDocument(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IOException {
String filename= file.getOriginalFilename();
//进行获取后缀名
String subFilename= filename.substring(filename.lastIndexOf("."));
File filePath=new File("E:\\huang\\");
if (!filePath.exists()){
filePath.mkdir();
}
String realFilename=UUID.randomUUID()+subFilename;
File realPath=new File(filePath+realFilename);
try{
file.transferTo(realPath);
}catch (Exception e){
e.printStackTrace();
}