Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作
代碼
參數(shù):
1.filePath:文件的絕對(duì)路徑(d:\download\a.xlsx)
2.fileName(a.xlsx)
3.編碼格式(GBK)
4.response、request不介紹了,從控制器傳入的http對(duì)象
代碼片.
//控制器
@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)
public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {
boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);
if(is)
System.out.println("成功");
else
System.out.println("失敗");
}
//下載方法
public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){
File f = new File(filePath);
if (!f.exists()) {
try {
response.sendError(404, "File not found!");
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
String type = fileName.substring(fileName.lastIndexOf(".") + 1);
//判斷下載類(lèi)型 xlsx 或 xls 現(xiàn)在只實(shí)現(xiàn)了xlsx、xls兩個(gè)類(lèi)型的文件下載
if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){
response.setContentType("application/force-download;charset=UTF-8");
final String userAgent = request.getHeader("USER-AGENT");
try {
if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE瀏覽器
fileName = URLEncoder.encode(fileName, "UTF8");
} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐瀏覽器
fileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "UTF8");// 其他瀏覽器
}
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
return false;
}
InputStream in = null;
OutputStream out = null;
try {
//獲取要下載的文件輸入流
in = new FileInputStream(filePath);
int len = 0;
//創(chuàng)建數(shù)據(jù)緩沖區(qū)
byte[] buffer = new byte[1024];
//通過(guò)response對(duì)象獲取outputStream流
out = response.getOutputStream();
//將FileInputStream流寫(xiě)入到buffer緩沖區(qū)
while((len = in.read(buffer)) > 0) {
//使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到瀏覽器
out.write(buffer,0,len);
}
//這一步走完,將文件傳入OutputStream中后,頁(yè)面就會(huì)彈出下載框
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
} finally {
try {
if (out != null)
out.close();
if(in!=null)
in.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
return true;
}else {
logger.error("不支持的下載類(lèi)型!");
return false;
}
}
實(shí)現(xiàn)效果
1.火狐瀏覽器效果

2.chrome效果,自動(dòng)下載

補(bǔ)充知識(shí):文件上傳/下載的幾種寫(xiě)法(java后端)
文件上傳
1、框架已經(jīng)幫你獲取到文件對(duì)象File了
public boolean uploadFileToLocale(File uploadFile,String filePath) {
boolean ret_bl = false;
try {
InputStream in = new FileInputStream(uploadFile);
ret_bl=copyFile(in,filePath);
} catch (Exception e) {
e.printStackTrace();
}
return ret_bl;
}
public boolean copyFile(InputStream in,String filePath) {
boolean ret_bl = false;
FileOutputStream os=null;
try {
os = new FileOutputStream(filePath,false);
byte[] b = new byte[8 * 1024];
int length = 0;
while ((length = in.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
in.close();
ret_bl = true;
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(os!=null){
os.close();
}
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret_bl;
}
}
2、天了個(gè)擼,SB架構(gòu)師根本就飄在天空沒(méi)下來(lái),根本就沒(méi)想文件上傳這一回事
public String uploadByHttp(HttpServletRequest request) throws Exception{
String filePath=null;
List<String> fileNames = new ArrayList<>();
//創(chuàng)建一個(gè)通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請(qǐng)求
if(multipartResolver.isMultipart(request)){
//轉(zhuǎn)換成多部分request
MultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request);
MultiValueMap<String,MultipartFile> multiFileMap = multiRequest.getMultiFileMap();
List<MultipartFile> fileSet = new LinkedList<>();
for(Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){
fileSet = temp.getValue();
}
String rootPath=System.getProperty("user.dir");
for(MultipartFile temp : fileSet){
filePath=rootPath+"/tem/"+temp.getOriginalFilename();
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
fileNames.add(temp.getOriginalFilename());
temp.transferTo(file);
}
}
}
3、神啊,我正在擼框架,請(qǐng)問(wèn)HttpServletRequest怎么獲?。。。?!
(1)在web.xml中配置一個(gè)監(jiān)聽(tīng)
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
文件下載(直接用鏈接下載的不算),這比較簡(jiǎn)單
1、本地文件下載(即文件保存在本地)
public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {
response.setCharacterEncoding("UTF-8");
//設(shè)置ContentType字段值
response.setContentType("text/html;charset=utf-8");
//通知瀏覽器以下載的方式打開(kāi)
response.addHeader("Content-type", "appllication/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
//通知文件流讀取文件
InputStream in = request.getServletContext().getResourceAsStream(filePath);
//獲取response對(duì)象的輸出流
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
//循環(huán)取出流中的數(shù)據(jù)
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
}
2、遠(yuǎn)程文件下載(即網(wǎng)上資源下載,只知道文件URI)
public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){
try {
urlStr=urlStr.replaceAll("\\\\", "/");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設(shè)置超時(shí)間為3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403錯(cuò)誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到輸入流
InputStream inputStream = conn.getInputStream();
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));
//獲取響應(yīng)報(bào)文輸出流對(duì)象
//獲取response對(duì)象的輸出流
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
//循環(huán)取出流中的數(shù)據(jù)
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
以上這篇Java后臺(tái)Controller實(shí)現(xiàn)文件下載操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java基于rest assured實(shí)現(xiàn)接口測(cè)試過(guò)程解析
這篇文章主要介紹了Java基于rest assured實(shí)現(xiàn)接口測(cè)試過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
手把手帶你分析SpringBoot自動(dòng)裝配完成了Ribbon哪些核心操作
這篇文章主要介紹了詳解Spring Boot自動(dòng)裝配Ribbon哪些核心操作的哪些操作,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08
java?fastjson傳輸long數(shù)據(jù)卻接收到了int的問(wèn)題
這篇文章主要介紹了java?fastjson傳輸long數(shù)據(jù)卻接收到了int的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot項(xiàng)目中java -jar xxx.jar沒(méi)有主清單屬性的解決方法
這篇文章主要給大家介紹了SpringBoot項(xiàng)目中java -jar xxx.jar沒(méi)有主清單的解決方法,文中通過(guò)代碼示例給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-01-01
Java的JDBC中Statement與CallableStatement對(duì)象實(shí)例
這篇文章主要介紹了Java的JDBC中Statement與CallableStatement對(duì)象實(shí)例,JDBC是Java編程中用于操作數(shù)據(jù)庫(kù)的API,需要的朋友可以參考下2015-12-12
java+mysql實(shí)現(xiàn)商品搶購(gòu)功能
這篇文章主要為大家詳細(xì)介紹了java+mysql實(shí)現(xiàn)商品搶購(gòu)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
利用?SpringBoot?在?ES?中實(shí)現(xiàn)類(lèi)似連表查詢(xún)功能
這篇文章主要介紹了如何利用?SpringBoot?在?ES?中實(shí)現(xiàn)類(lèi)似連表的查詢(xún)功能,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07

