SpringBoot文件上傳下載
阿新 • • 發佈:2019-04-01
isp rac actor map 單個 檢測 buffere resp 獲取
新建springboot項目,前臺頁面使用的thymeleaf模板,其余的沒有特別的配置,pom代碼如下:
前臺頁面index.html,其中包含單個上傳,下載,批量上傳。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>單文件上傳</p> <form action="upload" method="POST" enctype="multipart/form-data"> 文件:<input type="file" name="file"/> <input type="submit"/> </form> <hr/> <p>文件下載</p> <a href="download">下載文件</a> <hr/> <p>多文件上傳</p> <form method="POST" enctype="multipart/form-data" action="batch"> <p>文件1:<input type="file" name="file"/></p> <p>文件2:<input type="file" name="file"/></p> <p><input type="submit" value="上傳"/></p> </form> </body> </html>
IndexController只是用來頁面的跳轉
package com.dalaoyang.Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.Controller * @email [email protected] * @date 2018/4/9*/ @Controller public class IndexController { @RequestMapping("/") public String index() { return "index"; } }
FileController,其中包含單個上傳,單個下載,批量上傳對應的方法
@RestController public class FileController { private static final Logger log = LoggerFactory.getLogger(FileController.class); @RequestMapping(value = "/upload") public String upload(@RequestParam("file") MultipartFile file) { try { if (file.isEmpty()) { return "文件為空"; } // 獲取文件名 String fileName = file.getOriginalFilename(); log.info("上傳的文件名為:" + fileName); // 獲取文件的後綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); log.info("文件的後綴名為:" + suffixName); // 設置文件存儲路徑 String filePath = "/Users/dalaoyang/Downloads/"; String path = filePath + fileName; File dest = new File(path); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs();// 新建文件夾 } file.transferTo(dest);// 文件寫入 return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; } @PostMapping("/batch") public String handleFileUpload(HttpServletRequest request) { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); MultipartFile file = null; BufferedOutputStream stream = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); String filePath = "/Users/dalaoyang/Downloads/"; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); stream = new BufferedOutputStream(new FileOutputStream( new File(filePath + file.getOriginalFilename())));//設置文件路徑及名字 stream.write(bytes);// 寫入 stream.close(); } catch (Exception e) { stream = null; return "第 " + i + " 個文件上傳失敗 ==> " + e.getMessage(); } } else { return "第 " + i + " 個文件上傳失敗因為文件為空"; } } return "上傳成功"; } @GetMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) { String fileName = "dalaoyang.jpeg";// 文件名 if (fileName != null) { //設置文件路徑 File file = new File("/Users/dalaoyang/Documents/dalaoyang.jpeg"); //File file = new File(realPath , fileName); if (file.exists()) { response.setContentType("application/force-download");// 設置強制下載不打開 response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } return "下載成功"; } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return "下載失敗"; } }
SpringBoot文件上傳下載