本人在 .NET 轉JAVA 的路上 ,也在學習SpringBoot相關知識,這裡記錄一下在Springboot中實現文件上傳下載的核心代碼 源碼下載地址: https://github.com/struggle0903/SpringBootfiledemo.git ...
本人在 .NET 轉JAVA 的路上 ,也在學習SpringBoot相關知識,這裡記錄一下在Springboot中實現文件上傳下載的核心代碼
package com.file.demo.springbootfile;
import com.file.util.ResultUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/*
* springboot整合vue,文件上傳下載
* */
//上傳不要用@Controller,用@RestController
@RestController
@RequestMapping("/file")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//在文件中,不用/或者\最好,推薦使用File.separator
private final static String fileDir="files";
private final static String rootPath = System.getProperty("user.home")+ File.separator+fileDir+File.separator;
/*
* 文件上傳
* */
@RequestMapping("/upload")
public Object uploadFile(@RequestParam("file")MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request){
File fileDir = new File(rootPath);
/*
* exists():測試此抽象路徑名錶示的文件是否存在
* isDirectory():檢查一個對象是否是文件夾
* isFile():判斷是否為文件,也可能是文件目錄
* */
if(!fileDir.exists() && !fileDir.isDirectory()){
//檢查到文件不存在則創建
fileDir.mkdir();//創建文件,一級
fileDir.mkdirs();//創建多級
}
try{
if(multipartFiles != null && multipartFiles.length > 0){
for ( int i = 0;i<multipartFiles.length;i++){
try{
String storagePath = rootPath+multipartFiles[i].getOriginalFilename();
logger.info("上傳的文件:" + multipartFiles[i].getName()+","+multipartFiles[i].getContentType()+","
+multipartFiles[i].getOriginalFilename() + ",保持的路徑為:" + storagePath);
Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
}catch (IOException e){
logger.info(ExceptionUtils.getFullStackTrace(e));
}
}
}
}catch (Exception e){
return ResultUtil.error(e.getMessage());
}
return ResultUtil.success("上傳成功!");
}
/*
* 文件下載
* */
@RequestMapping("/download")
public Object downkiadFile(@RequestParam String fileName,final HttpServletResponse response,final HttpServletRequest request){
OutputStream os = null;
InputStream is = null;
try{
//獲取輸出流rootPath
os = response.getOutputStream();
//重置輸出流
response.reset();
response.setContentType("application/x-download;charset=GBK");
response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "iso-8859-1"));
//讀取流
File f= new File(rootPath+fileName);
is = new FileInputStream(f);
if(is == null){
logger.error("下載文件失敗,請檢查文件“"+ fileName +"”是否存在");
return ResultUtil.error("下載附件失敗,請檢查文件“" + fileName + "”是否存在");
}
//複製文件
IOUtils.copy(is,response.getOutputStream());
//刷新緩衝
response.getOutputStream().flush();
}catch (IOException e){
return ResultUtil.error("下載文件失敗,error:" + e.getMessage());
}
//文件的關閉在finally中執行
finally {
{
try {
if(is != null){
is.close();
}
}catch (IOException e){
logger.error(ExceptionUtils.getFullStackTrace(e));
}
try{
if(os != null){
os.close();
}
}catch (IOException e){
logger.info(ExceptionUtils.getFullStackTrace(e));
}
}
}
return null;
}
}
源碼下載地址: https://github.com/struggle0903/SpringBootfiledemo.git