學(xué)習(xí)視頻:【編程不良人】2021年SpringBoot最新最全教程
第十二章、文件上傳、下載
文件上傳
文件上傳是指將文件從客戶(hù)端計(jì)算機(jī)傳輸?shù)椒?wù)器的過(guò)程。
-
上傳思路
- 前端的上傳頁(yè)面:提交方式必須為
post
,enctype
屬性必須為multipart/form-data
- 開(kāi)發(fā)后端的Controller
- 后端方法接收參數(shù)必須和前端標(biāo)簽的name名一致
- 前端的上傳頁(yè)面:提交方式必須為
-
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>文件上傳</title> </head> <body> <h1>測(cè)試文件上傳</h1> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上傳文件"> </form> </body> </html>
-
Controller
@Controller @RequestMapping("file") public class FileController { private final Logger log = LoggerFactory.getLogger(FileController.class); /** * 測(cè)試文件上傳 */ @RequestMapping("upload") public String upload(MultipartFile file, HttpServletRequest request) throws IOException { // 變量名要和form的input type="file"的name名一致 log.debug("文件名:{}", file.getOriginalFilename()); log.debug("文件大?。簕}", file.getSize()); log.debug("文件類(lèi)型:{}", file.getContentType()); // 處理文件上傳 根據(jù)相對(duì)路徑 上傳 upload 獲取絕對(duì)路徑(真實(shí)路徑) /users/desktop String realpath = request.getSession().getServletContext().getRealPath("/upload"); log.debug("獲取絕對(duì)路徑:{}", realpath); // 修改文件名 String fileName = file.getOriginalFilename(); int i = fileName.lastIndexOf("."); String suffix = fileName.substring(i); String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+suffix; // 上傳文件 參數(shù)1將文件寫(xiě)進(jìn)目錄 file.transferTo(new File(realpath,newFileName)); return "redirect:/upload.jsp"; } }
修改上傳文件大小限制
當(dāng)上傳文件超過(guò)10M則會(huì)報(bào)錯(cuò)
-
修改配置
spring: servlet: multipart: max-request-size: 120MB # 運(yùn)行請(qǐng)求傳遞文件大小 max-file-size: 120MB # 運(yùn)行服務(wù)器可以處理的最大文件大小
傳統(tǒng)上傳方式不適用于Jar包部署Linux
在傳統(tǒng)的Spring Boot 應(yīng)用程序中,當(dāng)你在 Linux 上通過(guò) JAR 包部署后,絕對(duì)路徑上傳文件會(huì)失效的原因是因?yàn)?JAR 包中的文件無(wú)法通過(guò)絕對(duì)路徑進(jìn)行訪(fǎng)問(wèn)。
-
修改上傳方式(文件上傳位置解耦合)
@Value("${file.upload.dir}") private String **realPath**; /** * 【推薦】適用于任何一種部署方式 * @param file * @return * @throws IOException */ @RequestMapping("uploadByJarDeploy") public String uploadByJarDeploy(MultipartFile file) throws IOException { log.debug("文件名:{}", file.getOriginalFilename()); log.debug("文件大?。簕}", file.getSize()); log.debug("文件類(lèi)型:{}", file.getContentType()); // 修改文件名 String fileName = file.getOriginalFilename(); int i = fileName.lastIndexOf("."); String suffix = fileName.substring(i); String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + suffix; // 文件上傳 file.transferTo(new File(**realPath**,newFileName)); return "redirect:/upload.jsp"; }
-
配置
# 指定文件上傳位置 file: upload: dir: D:\Desktop\test\photo
文件下載
文件下載是指從服務(wù)器獲取文件并保存到本地計(jì)算機(jī)或設(shè)備的過(guò)程。
-
開(kāi)發(fā)步驟
- 確定項(xiàng)目中哪些資源可以被下載
- 將可以被下載資源放入服務(wù)器指定位置
- 項(xiàng)目中開(kāi)發(fā)一個(gè)下載頁(yè)面/提供下載文件的鏈接
- 開(kāi)發(fā)下載controller
-
controller
@Controller @RequestMapping("file") public class FileController { private Logger log = LoggerFactory.getLogger(FileController.class); @Value("${file.download.dir}") private String realPath; /** * 文件下載 * @param fileName */ @RequestMapping("download") public void download(StringopenStyle, String fileName, HttpServletResponse response) throws IOException { openStyle=openStyle==null?"inline":"attachment"; log.debug("當(dāng)前下載文件名:{}", fileName); log.debug("當(dāng)前下載目錄:{}", realPath); // 1.指定目錄中讀取文件 File file = new File(realPath, fileName); // 2.將文件讀取為文件輸入流 FileInputStream is = new FileInputStream(file); // 3.獲取響應(yīng)輸出流 response.setContentType("text/plain;charset=UTF-8"); ServletOutputStream os = response.getOutputStream(); // 4.附件下載文件 attachment(附件) inline(在線(xiàn)打開(kāi)) response.setHeader("content-disposition",openStyle+";fileName=" + URLEncoder.encode(fileName,"UTF-8")); // 5.輸入流復(fù)制給輸出流 // 傳統(tǒng)寫(xiě)法 // int len = 0; // byte[] b = new byte[1024]; // while (true) { // len = is.read(b); // if (len == -1) { // break; // } // os.write(b, 0, len); // } // is.close(); // spring提供的復(fù)制方法,會(huì)自動(dòng)釋放is和os FileCopyUtils.copy(is, os); } }
-
download.jsp文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-760319.html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>下載</title> </head> <body> <h1>文件下載</h1> <ul> <li> help.md <a href="${pageContext.request.contextPath}/file/download?fileName=HELP.md">在線(xiàn)打開(kāi)</a> <a href="${pageContext.request.contextPath}/file/download?fileName=HELP.md&openStyle=attachment">附件下載</a> </li> <li> springmvc.png <a href="${pageContext.request.contextPath}/file/download?fileName=20231219161718427.png">在線(xiàn)打開(kāi)</a> <a href="${pageContext.request.contextPath}/file/download?fileName=20231219161718427.png&openStyle=attachment">附件下載</a> </li> </ul> </body> </html>
下一章:Spring Boot學(xué)習(xí)隨筆- 攔截器實(shí)現(xiàn)和配置(HandlerInterceptor、addInterceptors)、jar包部署和war包部署文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-760319.html
到了這里,關(guān)于Spring Boot學(xué)習(xí)隨筆- 文件上傳和下載(在線(xiàn)打開(kāi)、附件下載、MultipartFile)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!