首先,創建一個index.html頁面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
然後,在Controller中新建文件上傳方法
package com.example.demo.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class TestController {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");//根據日期創建文件分級目錄
@PostMapping("/upload")
public void upload(MultipartFile file,HttpServletRequest req) throws IOException {
String format = sdf.format(new Date());
String realPath = req.getServletContext().getRealPath("/img")+ format;//我們即將要保存的位置
System.out.println(realPath);
File folder = new File(realPath);
if(!folder.exists()){//判斷是否存在文件
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
file.transferTo(new File(folder,newName));//保存文件
String url = req.getScheme() + "//" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
System.out.println(url);//文件的訪問路徑
}
}
至此,我們的文件上傳功能已實現,我們還可以繼續在application.properties中增加一些文件屬性相關信息
#上傳的單個文件的大小
spring.servlet.multipart.max-file-size=1MB
#上傳的文件總大小
spring.servlet.multipart.max-request-size=10MB
#文件上傳臨時保存目錄
spring.servlet.multipart.location=
#文件上傳臨界值(超過這個臨界值,就要保存到location中去了)
spring.servlet.multipart.file-size-threshold=1MB