前言:
- 在項目webapp目錄下創建files文件夾,並在springmvc文件夾中配置靜態資源
<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>
2.files目錄下添加a.txt和test.zip

3.創建download.jsp
<a href="files/a.txt">下載</a>
啟動項目:

4.修改
<a href="files/test.zip">下載</a>
啟動項目:

根據兩者對比,總結:訪問資源時響應頭如果沒有設置Content-Disposition,瀏覽器默認按照inline值進行處理,也就是,能顯示就顯示,不能顯示就下載
正文:
- 導入依賴
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
2.修改超鏈接,並在配置文件中放行靜態資源files,前面已經寫過。
<a href="download?filename=test.zip">下載</a>
3.控制器開發
@RequestMapping("download") public void download(String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException{ //設置響應流文件進行下載 resp.setHeader("Content-Disposition","attachment;filename="+filename); ServletOutputStream sos = resp.getOutputStream(); File file = new File(req.getServletContext().getRealPath("files"), filename);//這個路徑為磁盤開始 byte[] bytes = FileUtils.readFileToByteArray(file); sos.write(bytes); sos.flush(); sos.close(); }
這樣,任意格式都會以文件的形式下載了》》》》
總結:修改響應頭中Context-Disposition="attachment;filename=文件名", attachment下載以附件的形式下載。
