1. 程式人生 > >SpringBoot多檔案上傳和檔案下載

SpringBoot多檔案上傳和檔案下載

1、前端的form表單:

<form id="form"  action="controller層的多檔案上傳方法訪問路徑" method="post" enctype="multipart/form-data">

<input  type="file" name="file"  multiple="multiple" >

</form>

<a href="controller層的檔案下載方法訪問路徑">下載</a>

2、在你的SRC-> main-> wabapp新建資料夾:

例:uploadfile

3、多檔案上傳Controller層方法

①、public  void  uploadfile(HttpServletRequest request, HttpServletResponse  response)

throws Exception {

List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

MultipartFile file = null;
for (MultipartFile multipartFile : files) {
file = multipartFile;
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
String filePath = request.getSession().getServletContext().getRealPath("uploadfile/");
try {
uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {

e.printStackTrace();

}

②、public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();

}

4、檔案下載Controller層方法

①、public void down(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName =“檔名”;
String filePhth = request.getSession().getServletContext().getRealPath("\\uploadfile") + "//"

+ fileName;

fileName = URLEncoder.encode(fileName, "UTF-8");
// 設定檔案下載頭
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
// 設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
downloadFile(fileName, filePhth, out);
}

}

②、public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
}