标签:
public class TestAction extends ActionSupport{
public String fileLoad() throws IOException{
String fileName = ServletActionContext.getRequest().getParameter("fileName");
//要处理中文乱码问题
fileName = new String(fileName.getBytes("iso8859-1"),"utf-8");
//要下载的哪个文件
String path = ServletActionContext.getServletContext().getRealPath("/");//得到项目的根目录
InputStream is = new FileInputStream(path+"/download/"+fileName);
//下载到哪里?客户端
HttpServletResponse response = ServletActionContext.getResponse();
OutputStream os = response.getOutputStream();
//弹出下载的框filename:提示用户下载的文件名
response.addHeader("content-disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName,"utf-8"));
byte[] b = new byte[1024];
int size = is.read(b);
while(size>0){
os.write(b,0,size);
size = is.read(b);
}
is.close();
os.close();
return null;
}
}
文件下载分为两步:读文件、写文件。从服务器读取,然后写到客户端去,所以需要InputStream和OutputStream。然后设置content-disposition弹出下载提示框,提示用户下载的文件名和从何处下载的。下面一段代码是读写文件的金典代码,我也不多讲了!
byte[] b = new byte[1024];
int size = is.read(b);
while(size>0){
os.write(b,0,size);
size = is.read(b);
}
<struts>
<package name="com.action" extends="struts-default">
<action name="download" class="com.action.FileLoadAction">
<result name="success" type="stream">
<param name="contentType">application/txt;</param>
<param name="inputName">downloadFile</param>
<param name="bufferSize">2048</param>
</result>
</action>
</package>
</struts>
public class FileLoadAction extends ActionSupport{
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) throws UnsupportedEncodingException {
this.fileName = new String(fileName.getBytes("iso8859-1"),"utf-8");
}
public InputStream getDownloadFile() throws UnsupportedEncodingException, FileNotFoundException{
//attachment为进行文件保存,这个时候还可以附件另一个参数filename表示保存时的缺省名称
//inline为在线打开,不进行保存
ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="+ java.net.URLEncoder.encode(fileName, "UTF-8"));
HttpServletResponse response = ServletActionContext.getResponse();
return new FileInputStream("d:/"+this.getFileName());
}
public String downloadFile(){
return SUCCESS;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<s:url value="download.action" var="url">
<s:param name="fileName">中文.txt</s:param>
</s:url>
<a href="${url }">点击下载</a>
action特殊的地方在于result的类型是一个流(stream),配置stream类型的结果时,因为无需指定实际的显示的物理资源,所以无需指定location属性,只需要指定inputName属性,该属性指向被下载文件的来源,对应着Action类中的某个属性,类型为InputStream,,struts2会寻找一个返回类型为InputStream的方法getInputStream()(方法名最好为getInputStream,有人说此方法名可以为别的可能需要与struts.xml中的inputName保存一致下面有解释,另一种理解:action中定义一个返回InputStream的方法,该方法作为被下载文件的入口,且需要配置stream类型结果时指定inputName参数,inputName参数的值就是方法去掉get前缀、首字母小写的字符串。
下面则列出了和下载有关的一些参数列表:
标签:
原文地址:http://www.cnblogs.com/giantfoot/p/5535671.html