Struts2完成文件的下载
第一步:
编写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//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'down.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">
<!--
<link rel="stylesheet"type="text/css" href="styles.css">
-->
</head>
<body>
<h1>文件下载</h1>
<!-- 下载链接 -->
<s:a action="down.action">download</s:a>
</body>
</html>
第二步:编写下载文件的Action文件
package cn.csdn.hr.up.action;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String inputPath;
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
/*
* 下载用的Action应该返回一个InputStream实例,该方法对应在result里的inputName属性为
* getDownloadFile
*/
public InputStream getDownloadFile()
{
return ServletActionContext.getServletContext().getResourceAsStream(
"/upload/Struts2.ppt");
}
@Override
public String execute() throws Exception
{
return SUCCESS;
}
}
第三步:
在struts2配置文件中定义action文件
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="down" extends="struts-default">
<action name="down"class="cn.csdn.hr.up.action.DownAction">
<!-- 配置结果类型为stream的结果 -->
<result name="success"type="stream">
<!-- 指定被下载文件的文件类型 -->
<param name="contentType">application/vnd.ms-powerpoint</param>
<!-- 指定下载文件的文件位置 -->
<param name="contentDisposition">filename="Struts2.ppt"</param>
<param name="inputName">downloadFile</param>
</result>
</action>
</package>
</struts>
测试点击download链接