SSH:动态下载文件

JSP

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></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">
</head>

<body>
	<a href="download.action?fileName=1.zip">下载</a>
	<br>
</body>
</html>

Action

package action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport{
    private String path;
    private String fileName;
    //此处省略set和get方法
    public InputStream getInputStream(){//此方法与struts.xml中的配置对应
         InputStream ins=null;
         /*try {//获取引用物理路径文件的输入流
	ins=new FileInputStream(new File(path+"/"+fileName));
          } catch (FileNotFoundException e) {
	e.printStackTrace();
          }*/
         //获取引用服务器逻辑路径文件的输入流
         ins=ServletActionContext.getServletContext().getResourceAsStream(path+"/"+fileName);
         return ins;
    }
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<package name="downfile2" extends="struts-default">
		<action name="download" class="action.DownloadAction">
 <!--  action静态参数,指定下载的文件路径,Web资源路径 -->
			<param name="path">/files</param>
			<!-- 使用StreamResult结果类型 -->
			<result type="stream">
				<!-- 指定下载的文件内容类型 -->
				<param name="contentType">application/octet-stream</param>
				<!-- Action用于读取文件内容的属性名,如果是inputStream,可以缺省 -->
				<param name="inputName">inputStream</param>
				<!-- 下载方式设置(inline-直接打开,attachment-打开对话框),默认文件名 -->
				<param name="contentDisposition">attachment;filename=${fileName}</param>
				<param name="bufferSize">1024</param>
			</result>
		</action>
	</package>
</struts>    

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>DownFile2</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/89010823
今日推荐