struts2实现文件的下载
1.首先写前台的页面,
<%@ 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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div>
<h4>文件下载</h4>
<s:url var="url" action="download"/>
<s:a href="%{url}">download files</s:a>
</div>
<s:fielderror></s:fielderror>
</body>
</html>
2.写后台的action,处理前台的请求
package cn.huas.struts2.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport
{
//该属性值在配置文件中指定,Struts2会自动进行注入(即赋值),需要为该属性提供setter和 getter方法
private String inputPath;//指定要下载的文件的完整路径(路径名+文件名)
/*
* 实现下载的Action类应该提供一个返回InputStream实例的方法,该方法对应在
<result.../>里的inputName属性值为targetFile
*/
public InputStream getTargetFile() throws Exception{
System.out.println(inputPath);
File file = new File(ServletActionContext.getServletContext().getRealPath("/" )+"upload/1.txt");
InputStream is = new FileInputStream(file);
return is;
//我这里将文件名写死了,其实可以通过inputPath来动态设置,但在这里访问总是出现
Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action. 的错误,到网上找了很多资料发现是inputName为null造成的后果,于是干脆不要它了。*/
3.配置struts.xml文件,
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.multipart.maxSize" value="10000000"></constant>
<constant name="struts.multipart.saveDir" value="e:/upload"/>
<package name="cn.huas.struts2.fileupload" extends="struts-default">
<action name="download" type="stream">
<!--指定下载文件的文件类型-->
<param name="contentType">text/plain</param>
<!--指定下载文件的文件位置-->
<param name="inputName">targetFile</param>
<!--指定下载文件的下载方式及下载时的保存文件名,filename保存时的文件名必须有扩展名,扩展名指示了下载类型的图标-->
<param name="contentDisposition">
attachment;filename=1.txt
</param>
<!--指定下载文件的缓冲区大小-->
<param name="bufferSize">4096</param>
</result>
</action>
</package>
</struts>
}
//处理用户请求的execute方法,该方法返回success字符串
public String execute() throws Exception{
return "success";
}
}
4,最后可以在浏览器里面测试看到一个超链接,当点击的时候就会出现下载的对话框。