简易版 :文件的下载

项目结构:

简易版 :文件的下载_第1张图片

~~~~~~~~~~~~~~~~~~·~~~~~~~~~~~~~~~分割线~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Action  DownLoadAction.java

package com.baidu.download;

import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private String	contentType; //结果类型
 	private long	contentLength; // 下载的文件的长度
 	private String	contentDisposition;//设定 Content-Dispositoin 响应头. 该响应头指定接应是一个文件下载类型, 一般取值为  attachment;filename="document.pdf".
 	private InputStream inputStream;
 	
	public String getContentType() {
		return contentType;
	}
	public long getContentLength() {
		return contentLength;
	}
	public String getContentDisposition() {
		return contentDisposition;
	}
	public InputStream getInputStream() {
		return inputStream;
	}
 	
	@Override
	public String execute() throws Exception {
		//确定各个成员变量的值
		contentType = "image/jpg";
		contentDisposition = "attachment;filename=wolf.jpg";
		
		ServletContext context  = ServletActionContext.getServletContext();
		
		
		String fileName = context.getRealPath("/files/wolf.jpg");
		inputStream = new FileInputStream(fileName);
		
		contentLength = inputStream.available();
		System.out.println(contentLength);
		return super.execute();
	}
	

}

配置:

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="testDownLoad" class="com.baidu.download.DownLoadAction">
			<!-- 
				下面三个参数需要动态提供
				contentType: 结果类型
				contentLength: 下载的文件的长度
				contentDisposition: 设定 Content-Dispositoin 响应头. 该响应头指定接应是一个文件下载类型, 一般取值为  attachment;filename="document.pdf".
			
				下面一个参数可以取默认值-
				inputName: 指定文件输入流的 getter 定义的那个属性的名字. 默认为 inputStream
			
				下面三个参数可以在struts.xml 中配置
				bufferSize: 缓存的大小. 默认为 1024
				allowCaching: 是否允许使用缓存  默认值:true
				contentCharSet: 指定下载的字符集 
				
			 -->
			<result type="stream">
				<param name="bufferSize">2048</param>
				<param name="allowCaching">true</param>
				<param name="contentCharSet">UTF-8</param>
			</result>
			
		
		</action>
		
	</package>

</struts>

页面:

download.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<a href="testDownload">Down Load </a>

</body>
</html>



你可能感兴趣的:(简易版 :文件的下载)