SpringMVC的檔案上傳和下載案例
阿新 • • 發佈:2021-09-03
上傳步驟
1. 引入依賴 commons-fileupload
2. 編寫上傳頁面
3. 表單 method="post" enctype="multipart/form-data" input type='file'
4. 編寫controller時考慮檔案重名問題,以及檔案在伺服器的絕對路徑
5. 編寫檔案上傳的解析器 id必須為multipartResolver
6. 測試
下載步驟
1. 編寫頁面
2. 設定響應物件的編碼
3. 測試
controller
package com.codegzy.controller; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; import java.time.LocalDate; import java.util.UUID; @Controller @RequestMapping("/file") public class FileController { @RequestMapping("/upload") public String upload(MultipartFile file, HttpServletRequest request){ String originalFilename = file.getOriginalFilename(); //獲取目錄在伺服器的絕對路徑 String realPath = request.getRealPath("/upload"); //防止檔案重名覆蓋問題 String extension = FilenameUtils.getExtension(originalFilename); String newfilename = UUID.randomUUID().toString().replace("-","") + "." + extension; //將不同天上傳的檔案分開 LocalDate now = LocalDate.now(); File dirdate = new File(realPath, now.toString()); if (!dirdate.exists()){ dirdate.mkdirs(); } try { file.transferTo(new File(dirdate,newfilename)); } catch (IOException e) { e.printStackTrace(); } return "index"; } @RequestMapping("/download") public void download(String openStyle,String filename, HttpServletRequest request, HttpServletResponse response) throws IOException { openStyle = openStyle == null ? "inline" : "attachment"; String realPath = request.getSession().getServletContext().getRealPath("/download"); //輸入流讀取檔案 FileInputStream inputStream = new FileInputStream(new File(realPath, filename)); //設定相應 response.setContentType("text/plain;charset=UTF-8"); //設定下載格式 attachment 附件 inline 線上 //對檔案進行編碼防止中文檔名亂碼問題 response.setHeader("content-disposition",openStyle + ";filename=" + URLEncoder.encode(filename,"UTF-8")); //獲取輸出流 ServletOutputStream outputStream = response.getOutputStream(); //利用工具類 IOUtils.copy(inputStream,outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); //傳統下載的方法 // int len = 0; // byte[] bytes = new byte[1024]; // while (true){ // len = inputStream.read(bytes); // if (len == -1) { // break; // } // outputStream.write(bytes,0,len); // } // inputStream.close(); // outputStream.close(); } @RequestMapping("/newfile") public String newfile(){ throw new RuntimeException("出錯了"); } }
springmvc.xml
<!-- 檔案上傳解析器-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!-- 限制檔案上傳最大為20M,超過20M報錯-->
<property name="maxUploadSize" value="20971520"/>
</bean>
頁面
<body> <h2>檔案上傳</h2> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上傳檔案"> </form> </body> <body> <h2>檔案下載</h2> abc.txt<a href="${pageContext.request.contextPath}/file/download?filename=abc.txt">線上開啟</a> <a href="${pageContext.request.contextPath}/file/download?filename=abc.txt&openStyle=a">附件下載</a> 自我接收.txt<a href="${pageContext.request.contextPath}/file/download?filename=自我接收.txt">線上開啟</a> <a href="${pageContext.request.contextPath}/file/download?filename=自我接收.txt&openStyle=a">附件下載</a> </body>