首先回憶一下springmvc中的文件上傳
1)引入文件上傳相關jar包,commons-io 、commons-fileupload
2)文件上傳表單提交方式必須為post
3)要求表單的enctype屬性必須為:multipart/form-data
4)后台接收文件時,使用multipartFile 變量與前端name屬性值保持一致
5)在springmvc的配置文件中必須加入,且id是框架規定寫死的。
<bean id="multipartResolver" class="CommonsMultipartResolver">
springboot中的文件上傳
1)在springboot項目中,自動引入了有關文件上傳的jar包 commons-io、commons-file
2)准備表單
提交方式:post enctype="multipart/form-data"
<form action="${pageContext.request.contextPath}/upload/test" method="post" enctype="multipart/form-data"> <input type="file" name="fileTest"/> <input type="submit" value="上傳"/>
</form>
3)后台控制器方法參數multipart 和 前台name屬性值保持一致
@Controller @RequestMapping("/upload") public class uploadController { @RequestMapping("/test") public String upload(MultipartFile fileTest, HttpServletRequest request) throws IOException { //獲取文件的原始名 String filename = fileTest.getOriginalFilename(); System.out.println(filename); //根據相對路徑獲取絕對路徑 String realPath = request.getSession().getServletContext().getRealPath("/upload"); fileTest.transferTo(new File(realPath,filename)); return "success"; } }
4)修改springboot中默認上傳文件大小(為1M)
#更改上傳文件的大小上限
http:
multipart:
max-file-size: 100MB //最大上限為100MB
max-request-size: 100MB //最大請求上限與max-file-size保持一致
springboot中的文件下載
1)頁面中提供一個下載的鏈接
<a href="${pageContext.request.contextPath}/download/test?fileName=idea快捷鍵.txt">點我下載</a>
2)開發下載文件的controller
下載文件的過程是一個讀寫操作,將文件讀入輸入流,然后通過輸出流讀出,讀出的時候動態設置響應類型
@Controller @RequestMapping("/download") public class downloadController { @RequestMapping("/test") public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception { //獲取文件的絕對路徑 String realPath = request.getSession().getServletContext().getRealPath("upload"); //獲取輸入流對象(用於讀文件) FileInputStream fis = new FileInputStream(new File(realPath, fileName)); //獲取文件后綴(.txt) String extendFileName = fileName.substring(fileName.lastIndexOf('.')); //動態設置響應類型,根據前台傳遞文件類型設置響應類型 response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName)); //設置響應頭,attachment表示以附件的形式下載,inline表示在線打開 response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(fileName,"UTF-8")); //獲取輸出流對象(用於寫文件) ServletOutputStream os = response.getOutputStream(); //下載文件,使用spring框架中的FileCopyUtils工具 FileCopyUtils.copy(fis,os); } }