文件下载是一个很常见的功能,用struts2实现文件下载的步骤:
一)定义一个action类,filedownload.java
package com.struts2.filedownload;
import java.io.inputstream;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actionsupport;
//文件下载
public class filedownload extends actionsupport{
private int number ;
private string filename;
public int getnumber() {
return number;
}
public void setnumber(int number) {
this.number = number;
public string getfilename() {
return filename;
public void setfilename(string filename) {
this.filename = filename;
//返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流
public inputstream getdownloadfile() throws exception
{
if(1 == number)
{
this.filename = "dream.jpg" ;
//获取资源路径
return servletactioncontext.getservletcontext().getresourceasstream("upload/dream.jpg") ;
}
else if(2 == number)
this.filename = "jd2chm源码生成chm格式文档.rar" ;
//解解乱码
this.filename = new string(this.filename.getbytes("gbk"),"iso-8859-1");
return servletactioncontext.getservletcontext().getresourceasstream("upload/jd2chm源码生成chm格式文档.rar") ;
else
return null ;
@override
public string execute() throws exception {
return success;
}
二)在struts.xml文件中配置相关信息
<struts>
<package name="struts2" extends="struts-default">
<action name="filedownload" class="com.struts2.filedownload.filedownload">
<result name="success" type="stream">
<param name="contenttype">text/plain</param>
<param name="contentdisposition">attachment;filename="${filename}"</param>
<param name="inputname">downloadfile</param>
<param name="buffersize">1024</param>
</result>
</action>
</package>
</struts>
1.结果类型必须要写成 type="stream" ,与之对应的处理类是 org.apache.struts2.dispatcher.streamresult
2.涉及到的参数:
3.
1) <param name="contentdisposition">attachment;filename="${filename}"</param>
contentdisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开,不能直接打开的才会打开下载框自己选择
2) attachment :下载时会打开下载框
3) filename="${filename}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字
4.<param name="inputname">downloadfile</param>,这个downloadfile名字要和filedownload.java类中的getdownloadfile()方法名去掉get 一致
三)用于显示下载的链接界面 filedownload.jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%
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 'filedownload.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>
<h2>文件下载内容:</h2><br/>
dream.jpg:<a href="filedownload.action?number=1">点击下载</a><br/>
jd2chm源码生成chm格式文档.rar:<a href="filedownload.action?number=2">点击下载2</a>
</body>
</html>