配置xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="down" namespace="/down" extends="struts-default">
<action name="down_*" class="star.july.a_download.DownloadAction" method="{1}">
<!-- 配置下载视图:stream -->
<result name="down" type="stream">
<!-- 给视图注入参数 -->
<!-- 弹出框内容 -->
<param name="contentDisposition">${fileName}</param>
<!-- 一次读取文件大小 -->
<param name="buffersize">512</param>
<!-- 提供需要下载的文件 -->
<param name="inputName">fileContext</param>
</result>
</action>
</package>
</struts>
编写Action类:
</pre><pre name="code" class="java">package star.july.a_download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport {
File file = null;
// 设置下载文件内容
public InputStream getFileContext() {
try {
file = new File(
"C:/Users/Starjuly/Pictures/Saved Pictures/拿画笔的女孩.jpg");
InputStream in = new FileInputStream(file);
return in;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
// 返回文件名称
public String getFileName() {
try {
String disposition ="";
HttpServletRequest request = ServletActionContext.getRequest();
//获取文件头
String head = request.getHeader("User-Agent");
if(head.contains("firefox")){
//火狐浏览器
//火狐浏览器要在=号前加*才能识别中文
disposition += "attachment;fileName*=";
}
else{
//非火狐
disposition += "attachment;fileName=";
}
String name = file.getName();
//解决文件的中文名问题
String str = URLEncoder.encode(name, "utf-8");
return disposition+str;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public String down() {
// 返回一个下载视图
return "down";
}
}