Struts2文件下載
1.傳統下載
public class DownloadAction extends ActionSupport {
private String fileName;//文件名稱
public void setFileName(String fileName) {
if (ServletActionContext.getRequest().getMethod().equals("GET")) {
try {
byte[] bytes = fileName.getBytes("ISO8859-1");//將get方式提交的中文進行處理,即將編碼由ISO8859-1轉為utf-8
fileName = new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
this.fileName = fileName;
}
// 下載
public String execute() throws Exception {
// 1.傳統下載方式
// 取得HttpServletResponse對象
HttpServletResponse response = ServletActionContext.getResponse();
// 取得ServletContext對象
ServletContext context = ServletActionContext.getServletContext();
// 通知瀏覽器以下載方式打開文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
// 取得需要下載文件的根目錄
String realPath = context.getRealPath("/WEB-INF/download");
// 構造子節輸入流
InputStream is = new FileInputStream(realPath + "/" + fileName);
// 構造子節輸出流
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) > 0) {
os.write(b, 0, len);
}
is.close();
os.close();
return SUCCESS;
}
}
2.文件下載
public class DownloadStreamAction extends ActionSupport { private static final long serialVersionUID = -2747191035343710583L; private String fileName; public void setFileName(String fileName) throws Exception { if(ServletActionContext.getRequest().getMethod().equals("GET")){ byte[] bytes = fileName.getBytes("ISO8859-1"); fileName=new String(bytes,"utf-8"); } this.fileName = fileName; } public String getFileName() throws Exception { return URLEncoder.encode(fileName, "utf-8"); } public InputStream getImageStream() throws Exception { InputStream inputStream = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/download/"+fileName); return inputStream; } }
<package name="download" extends="struts-default"> <action name="DownloadAction" class="download.DownloadStreamAction" method="execute"> <!-- 以stream二進制流的方式打開 --> <result name="success" type="stream"> <!-- 指明文件的下載類型 --> <param name="contentType">image/jpeg</param> <!-- 指明如果取得需要下載文件的InputStream輸入流 --> <param name="inputName">imageStream</param> <!-- 指明讓瀏覽器以下載框的方式打開 --> <param name="contentDisposition">attachment;filename="building.jpg"</param> <!--<param name="contentDisposition">attachment;filename=${fileName}</param>--> <!-- 指明下載文件時的字符數組byte[]大小 --> <param name="bufferSize">1024</param> </result> </action> </package>
轉載自:https://www.cnblogs.com/amosli/p/3547414.html
Struts2文件下載