struts2文件下載
來源:程序員人生 發(fā)布時間:2015-06-16 08:15:16 閱讀次數(shù):2647次
有些時候,如果我們提供的下載文件包括中文名稱,直接給出該地址會報錯。這時候我們就需要自己寫1個action來實現(xiàn)文件下載的功能。
前臺界臉部分:
<%@ page language="java" contentType="text/html; charset=UTF⑻"
pageEncoding="UTF⑻"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">
<!-- 導(dǎo)入struts2標簽庫 -->
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF⑻">
<title>上傳成功</title>
</head>
<body>
<a href="downLoadAction.action">下載word文檔</a>
</body>
</html>
action部份:
package com.hcj.action;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.hcj.model.Book;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownLoadAction extends ActionSupport {
//該屬性是依賴注入的屬性,可以在配置文件中動態(tài)指定該屬性值
private String inputPath;
//依賴注入該屬性之的setter方法
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
/*
* 定義1個返回InputStream的方法
* 該方法將作為被下載文件的入口,
* 且需要配置stream類型結(jié)果時指定inputName參數(shù)
* inputSteam參數(shù)的值就是方法去掉get前綴,首字母小寫的字符串
*/
public InputStream getTargetFile() throws Exception {
//返回指定文件對得輸入流
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
struts.xml配置:
<action name="downLoadAction" class="com.hcj.action.DownLoadAction">
<!-- 指定被下載資源的位置 -->
<param name="inputPath">/upload/實習(xí)生計劃-張某某.docx</param>
<!-- 配置結(jié)果類型為stream的結(jié)果 -->
<result name="success" type="stream">
<!-- 指定被下載文件的文件類型(此處為后綴為.docx的word文檔) -->
<param name="contentType">application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
<!-- 指定由getTargetFile()方法被下載文件的inputStream -->
<param name="inputName">targetFile</param>
<param name="contentDisposition">filename="test.docx"</param>
<!-- 指定下載文件緩沖大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈