Struts2文件下载

来源:互联网 发布:域名代理商源码 编辑:程序博客网 时间:2024/05/17 04:35

首先是action

package action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.Action;public class FileDownloadAction implements Action {private String filename;public String getFilename() {return filename;}public void setFilename(String filename) {this.filename = filename;}public InputStream getTargetFile() throws FileNotFoundException {File file = new File("E:\\jj.txt");//指定下载文件名setFilename(file.getName());return new FileInputStream(file);}public String execute() throws Exception {// TODO Auto-generated method stubreturn SUCCESS;}}

接着是struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><package name="lee" extends="struts-default"><action name="download" class="action.FileDownloadAction"><result name="success" type="stream"><!-- 指定下载文件类型 --><param name="contentType">text/plain</param><!-- 指定下载文件位置,必须和InputStream getTargetFile()中的get后的名字相同,首字母变小写 --><param name="inputName">targetFile</param><!-- 下载时显示的文件名 --><param name="contentDisposition">attachment;filename="${filename}"</param><!-- 指定下载文件的缓冲大小 --><param name="bufferSize">4096</param></result></action></package></struts>    

然后,是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 '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>  <h2>文件下载的内容</h2>  第一个文件:<a href="lee/download.action">点击下载</a>  </body></html>


 

0 0
原创粉丝点击