标签:
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.编写下载文件的action。(做测试前现在WebRoot路径下建一个upload文件夹,里面放你要下载文件)该类为FileDownload.action</span>
<pre name="code" class="java">package com.zhaoyun.business.action;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.zhaoyun.core.web.struts2.BaseAction;
public class FileDownload extends BaseAction {
private static final long serialVersionUID = 1L;
//文件下载
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
//返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流
public InputStream getDownloadFile() throws Exception
{
return ServletActionContext.getServletContext().getResourceAsStream("upload/"+fileName);
}
@Override
public String execute() throws Exception {
System.out.println("execute");
return SUCCESS;
}
}2.配置访问的路径。在struts.xml中配置
<action name="FileDownload" class="com.zhaoyun.business.action.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>
3.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> <span style="white-space:pre"> </span><meta http-equiv="pragma" content="no-cache"> <span style="white-space:pre"> </span><meta http-equiv="cache-control" content="no-cache"> <span style="white-space:pre"> </span><meta http-equiv="expires" content="0"> <span style="white-space:pre"> </span><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <span style="white-space:pre"> </span><meta http-equiv="description" content="This is my page"> <span style="white-space:pre"> </span><!-- <span style="white-space:pre"> </span><link rel="stylesheet" type="text/css" href="styles.css"> <span style="white-space:pre"> </span>--> </head> <body> <h2>文件下载内容:</h2><br/> welcome.gif:<a href="FileDownload.action?fileName=welcome.gif">点击下载</a><br/> 计算机论文1.docx:<a href="FileDownload.action?fileName=计算机论文1.docx">点击下载2</a> Dubbo实战.pdf:<a href="FileDownload.action?fileName=Dubbo实战.pdf">点击下载2</a> </body> </html>
这样一个简单的文件下载demo就完成了。
标签:
原文地址:http://blog.csdn.net/fubo1990/article/details/51350606