前言
不關是用Java開發什麼程式,或多或少都會使用到檔案的上傳和下載下傳啊。比如圖檔檔案,excel檔案,錯誤檔案是什麼的。是以,能簡單,快捷的實作對檔案的上傳和下載下傳,或者有一個自己的模闆,用到的時候來取,是一件很友善的事情。今天小編就帶領大家使用springboot來搭建檔案的上傳和下載下傳的模闆。
一,搭建一個springboot的開發環境
以下是springboot的pow.xml依賴
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.wyl
SpringBootFile
0.0.1-SNAPSHOT
jar
SpringBootFile
http://maven.apache.org
UTF-8
1.7
org.springframework.boot
spring-boot-starter-parent
1.5.3.RELEASE
junit
junit
3.8.1
test
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
2、application.properties檔案中取消模闆檔案緩存
spring.thymeleaf.cache=false
3、編寫模闆檔案
file.html
Insert title here
檔案上傳
選擇檔案:
multifile.html
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
Insert title here
檔案上傳
選擇檔案1:
選擇檔案2:
選擇檔案3:
4、編寫Controller
@Controller
public class FileUploadController {
@RequestMapping("file")
public String file(){
return "/file";
}
@RequestMapping("fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file){
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
String path = "F:/test" ;
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //儲存檔案
return "true";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
@RequestMapping("multifile")
public String multifile(){
return "/multifile";
}
@RequestMapping(value="multifileUpload",method=RequestMethod.POST)
public @ResponseBody String multifileUpload(HttpServletRequest request){
List files = ((MultipartHttpServletRequest)request).getFiles("fileName");
if(files.isEmpty()){
return "false";
}
String path = "F:/test" ;
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
}
return "true";
}
}
五 遇見的問題
可能你再上傳檔案的時候遇見一個問題,就是我們上傳的檔案被限制了檔案的大小。
org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException:
The field fileName exceeds its maximum permitted size of 1048576 bytes.
SpringBoot的預設上傳檔案的大小是2m 如果你上傳的檔案超過了2m就會出現這樣的錯誤。
這個時候我們可以再application.properties裡面進行修改
# Single file max size
multipart.maxFileSize=50Mb
# All files max size
multipart.maxRequestSize=50Mb
但是,這樣有可能解決不了問題。
這個是時候我們需要在配置檔案裡面修改下配置檔案。
建立一個類,加上@Configuration檔案進行說明,這是一個配置類。
然後在類裡面加上
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//factory.setMaxFileSize(1024);
//單個檔案最大
factory.setMaxFileSize("10240KB"); //KB,MB
/// 設定總上傳資料總大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
@Bean這個注解會把return 的那個類裝到spring的bean工廠裡面,這樣springboot在啟動的時候,掃描到這個類就會進行相應配置的修改。
6 檔案的下載下傳
@RequestMapping("/download")
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename="2.xlsx";
String filePath = "D:/download" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){ //判斷檔案父目錄是否存在
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //檔案輸入流
BufferedInputStream bis = null;
OutputStream os = null; //輸出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download---" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
image.png