javaweb 實現(xiàn)文件下載的方法及實例代碼
javaweb 實現(xiàn)文件下載
不要再說用<a>標(biāo)簽下載了,這個會把文件打開而不是下載
例如:
<a href="E:\MyDesktop\37fecd65330184de67d419a8d02e7081.jpg">下載</a>
如果我這樣寫,瀏覽器就會把圖片直接打開,除非是一個瀏覽器打不開的文件
所以我們還是要用到j(luò)ava本身的文件讀寫來進行文件的下載
<a href="downloadFile?filename=<s:property value='document_filename'/>">下載</a>
package com.cpsec.tang.chemical.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import com.cpsec.tang.chemical.biz.DocumentBiz;
import com.cpsec.tang.chemical.entity.Document;
import com.cpsec.tang.chemical.util.Pager;
import com.opensymphony.xwork2.ActionSupport;
@Controller("documentAction")
public class DocumentAction extends ActionSupport{private String filename;
public String downloadFile(){
System.out.println(filename);
try {
HttpServletResponse response=ServletActionContext.getResponse();
//設(shè)置文件MIME類型
response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));
//設(shè)置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//獲取目標(biāo)文件的絕對路徑
String fullFileName = ServletActionContext.getServletContext().getRealPath("/files/" + filename);
//System.out.println(fullFileName);
//讀取文件
InputStream in = new FileInputStream(fullFileName);
//讀取目標(biāo)文件,通過response將目標(biāo)文件寫到客戶端
OutputStream out = response.getOutputStream();
//寫文件
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
IntelliJ IDEA遠程Debug Linux的Java程序,找問題不要只會看日志了(推薦)
這篇文章主要介紹了IntelliJ IDEA遠程Debug Linux的Java程序,找問題不要只會看日志了,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
java中處理json各種各樣的轉(zhuǎn)換方法(推薦)
下面小編就為大家分享一篇java中處理json各種各樣的轉(zhuǎn)換方法小結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11
springboot整合websocket后啟動報錯(javax.websocket.server.ServerCont
這篇文章主要介紹了springboot整合websocket后啟動報錯(javax.websocket.server.ServerContainer not available),通過分析錯誤信息、排查代碼和配置,找出問題的根源,并給出相應(yīng)的解決方案,感興趣的可以了解一下2024-01-01
testNG項目通過idea Terminal命令行執(zhí)行的配置過程
這篇文章主要介紹了testNG項目通過idea Terminal命令行執(zhí)行,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07
Python實現(xiàn)filter函數(shù)實現(xiàn)字符串切分
這篇文章主要介紹了Python實現(xiàn)filter函數(shù)實現(xiàn)字符串切分,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03

