struts2文件下载

struts2实现文件下载功能:
   首先action

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadFile extends ActionSupport {
	private String fileName;
	private String savePath = "/upload";

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName)
			throws UnsupportedEncodingException {
		this.fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
		// 中文支持设置
	}

	public InputStream getInputStream() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ java.net.URLEncoder.encode(fileName, "UTF-8"));
		/**
		 * 上面两句是实现中文支持
		 */
		String dir = savePath + "/" + fileName;
		InputStream in = ServletActionContext.getServletContext()
				.getResourceAsStream(dir);
		return in;
		/**
		 * 如果你遇到java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name 
                  [inputStream] in the invocation stack. Check the tag specified for this action. 
		 * 
		 * 恭喜你,你的路径可能错误,得到的in为null。
		 * 
		 * 如果dir是绝对路径   
		 * return new FileInputStream(dir); 
		 * 如果dir是Resource下的相对路径
		 * return ServletActionContext.getServletContext().getResourceAsStream(dir);
		 */

	}

	public String execute() throws Exception {
		return SUCCESS;

	}
}

struts 配置:

<action name="downLoad" class="DownloadFile">
			<!-- 要注意result的类型是stream -->
			<result name="success" type="stream">
				<!-- inputName参数指定文件的源头,根据这个配置,找getDownloadFile方法获得文件流 -->
				<param name="inputName">inputStream</param>
				<!-- 指定下载的方式,默认的是inline,这种方式,浏览器如果能打开的文件的话,就直接打开,而不会下载(如.txt格式文件)。一般指定是attachment方式,让用户可以选择是打开还是下载。 -->
				<!-- 如果像这样,action里必须提供fileName的get方法 ,当然你也可以给定好。-->
				<param name="contentDisposition">
					attachment;fileName="${fileName }"
				</param>
				<!-- 还可以指定文件的格式,缓冲大小 -->
				<param name="bufferSize">2048</param>
			</result>
		</action>


 

jsp页面:

 <a href="downLoad.action?fileName=${fileName }">${fileName }"</a>

参考博文: struts2实现文件的上传、下载struts2文件下载出现Can not find a java.io.InputStream with the name的错误 JSP、Struts2下载中文文件名乱码问题处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值