網站首頁 編程語言 正文
配置文件
SpringMVC 配置和依賴:http://www.shdianci.com/article/6537.html
文件下載的 Controller
注意:restFul 風格一般會把文件后綴名截取掉, 加上 :.+
來保留文件后綴名
package com.pro.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
@RestController
public class FileController {
// 使用restFul風格一般會把文件后綴名截取掉, 加上:.+ 來保留文件后綴名
@RequestMapping(value = "/download/{fileName:.+}")
public String download(@PathVariable String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
System.out.println("download --> " + fileName);
//要下載的圖片地址
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path, fileName);
if (!file.exists()) {
return "文件不存在";
}
//1、設置response 響應頭
response.reset(); //設置頁面不緩存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符編碼
response.setContentType("multipart/form-data"); //二進制傳輸數據
//設置響應頭
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
//2、 讀取文件--輸入流
InputStream input = new FileInputStream(file);
//3、 寫出文件--輸出流
OutputStream out = response.getOutputStream();
//4、執行 寫出操作
byte[] buff = new byte[1024];
int index = 0;
while ((index = input.read(buff)) != -1) {
out.write(buff, 0, index);
out.flush();
}
// 關閉流
out.close();
input.close();
return null;
}
}
測試
啟動項目訪問:http://localhost:8080/download/xxx.xx
我的項目中有一個 aa.pdf 的文件, 就直接訪問
http://localhost:8080/download/aa.pdf
原文鏈接:https://blog.csdn.net/weixin_44953227/article/details/113479130
相關推薦
- 2022-11-13 MacOS下C++使用WebRTC注意事項及問題解決_C 語言
- 2022-12-30 pytorch中nn.RNN()匯總_python
- 2022-12-15 C#利用KPM算法解決字符串匹配問題詳解_C#教程
- 2022-06-22 C#操作ini文件的幫助類_C#教程
- 2023-04-04 python中class(object)的含義是什么以及用法_python
- 2022-08-23 C++?primer超詳細講解關聯容器_C 語言
- 2022-08-19 mv命令linux
- 2022-10-19 python列表[list]和元組(tuple)詳情_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支