JavaWeb----学习(39)----struts2----文件的下载

1. 某些应用程序里, 可能需要动态地把一个文件发送到用户的浏览器中, 而这个文件的名字和存放位置在编程时是无法预知的

2. Struts 专门为文件下载提供了一种 Stream 结果类型. 在使用一个 Stream 结果时, 不必准备一个 JSP 页面.

     即,struts2中使用type="stream" 的result进行下载即可。

3.使用细节参看struts-2.3.15.3/docs/WW/docs/stream-result.html文档。

4. 可以为streamd的result设置如下的参数值:

        4.1 contentType:被下载的文件的 MIME 类型。默认值为 text/plain

        4.2 contentLength:被下载的文件的大小,以字节为单位

        4.3 contentDisposition 可以设置下载文件名的ContentDispositon 响应头,默认值为 inline

                                                通常设置为如下格式: attachment;filename="document.pdf".

       4.4  inputNameAction 中提供的文件的输入流。默认值为inputStream

       4.5 bufferSize:文件下载时缓冲区的大小。默认值为 1024

       4.6 allowCaching :文件下载时是否允许使用缓存。默认值为 true

       4.7 contentCharSet:文件下载时的字符编码。

 5. 以上的参数可以在Action中以getter方法的方式提供。

6. 下载文件例子。

    Action类 :TestDownload.java

package com.lishenhuan.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 TestDownload extends ActionSupport{


	 private String contentType;
	 private String contentDisposition;
	 private InputStream inputStream;
	 private long contentLength;

	 @Override
	public String execute() throws Exception {
		 //确定各个变量的值
		 contentType="text/html";     //准备下载的文件类型
		 contentDisposition="attachment;filename=lishenhuan.html";  //下载文件后的重命名

		 ServletContext servletContext = ServletActionContext.getServletContext();
		 String filename = servletContext.getRealPath("/file/warning.htm");
		 inputStream = new FileInputStream(filename);

		 contentLength = inputStream.available();
		 return super.execute();
	}

	public String getContentType() {
	    return contentType;
	}

	public String getContentDisposition() {
	    return contentDisposition;
	}

	public InputStream getInputStream() {
	    return inputStream;
	}
	public long getContentLength() {
	    return contentLength;
	}
}

      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="testUser" extends="struts-default">
		<action name="testDownload" class="com.lishenhuan.download.TestDownload">
			<result type="stream">
				<param name="bufferSize">2048</param>
			</result>
		</action>
	</package>
</struts>

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值