jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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-8">
<title>Insert title here</title>
</head>
<body>
<a href="upload/20161012_094556771_7237.doc">20161012_094556771_7237.doc</a><br/>
<a href="down?file=20161012_093223812_7769.jpg">20161012_093223812_7769.jpg</a>
</body>
</html>
action
package com.zucc.action;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownloadAction extends ActionSupport implements ServletContextAware{
private String file;
private InputStream is;
private ServletContext application;
private String downDir;
public String getFile() throws UnsupportedEncodingException {
//解决发送到网页文件名出现乱码的问题
return new String(this.file.getBytes("utf-8"),"ISO-8859-1");
}
public void setFile(String file) throws Exception {
//解决从网页获取文件名的乱码问题
this.file = new String(file.getBytes("ISO-8859-1"),"utf-8");
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
@Override
public String execute() throws Exception {
System.out.println("FileDownloadAction execute...");
System.out.println("file:"+file);
//获取文件路径
this.is = new FileInputStream(this.downDir + "/" + file);
return SUCCESS;
}
@Override
public void setServletContext(ServletContext context) {
this.application = context;
this.downDir = application.getRealPath("/upload");
}
}
struts.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>
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
<package name="default" namespace="/" extends="struts-default">
<action name="down" class="com.zucc.action.FileDownloadAction">
<result name="success" type="stream">
<!-- 这个is名字要和FileDownloadAction.java类中的类型为InputStream的变量名一致 -->
<param name="inputName">is</param>
<!-- 1) contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开
,不能直接打开的才会打开下载框自己选择
2) attachment :下载时会打开下载框
3) fileName="${fileName}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字
-->
<param name="contentDisposition">attachment;fileName="${file}"</param>
<!-- 一次性读取的字节大小 -->
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
注意:结果类型必须要写成 type="stream" ,与之对应的处理类是 org.apache.struts2.dispatcher.StreamResult