1.LoginAction,java
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
public class downLoadAction {
private InputStream is;
private String fileName;
public String execute() throws Exception{
fileName="1.jpg";
is=ServletActionContext.getServletContext()
.getResourceAsStream("/images/"+fileName);
fileName="萌宠.jpg";
fileName= new String(fileName.getBytes("utf-8"),"iso-8859-1");
return "success";
}
public InputStream getIs() {
return is;
}
public void setIs(InputStream is) {
this.is = is;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
2.struts2.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="xxx" extends="struts-default">
<action name="download" class="com.lanou3g.action.downLoadAction">
<result type="stream">
<param name="contentDisposition">attachment;filename=${fileName}
</param>
<param name="inputName">is</param>
</result>
</action>
</package>
</struts>
3.index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<a href="download">下载</a>
</body>
</html>