码迷,mamicode.com
首页 > 其他好文 > 详细

struts2文件下载

时间:2015-04-29 15:08:41      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:struts2

有些时候,如果我们提供的下载文件包含中文名称,直接给出该地址会报错。这时我们就需要自己写一个action来实现文件下载的功能。

前台界面部分:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<base href="<%=basePath%>">      
<!-- 导入struts2标签库 -->
<%@taglib prefix="s" uri="/struts-tags"%>
<!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=UTF-8">
<title>上传成功</title>
</head>
<body>

	<a href="downLoadAction.action">下载word文档</a>
</body>
</html>

action部分:

package com.hcj.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.hcj.model.Book;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {
	//该属性是依赖注入的属性,可以在配置文件中动态指定该属性值
	private String inputPath;
	
	//依赖注入该属性之的setter方法
	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	/*
	 * 定义一个返回InputStream的方法
	 * 该方法将作为被下载文件的入口,
	 * 且需要配置stream类型结果时指定inputName参数
	 * inputSteam参数的值就是方法去掉get前缀,首字母小写的字符串
	 */
	public InputStream getTargetFile() throws Exception {
		//返回指定文件对于得输入流
		return ServletActionContext.getServletContext().getResourceAsStream(inputPath); 
	}
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return SUCCESS;
	}
}

struts.xml配置:

<action name="downLoadAction" class="com.hcj.action.DownLoadAction">
			<!-- 指定被下载资源的位置 -->
			<param name="inputPath">/upload/实习生计划-洪陈金.docx</param>
			<!-- 配置结果类型为stream的结果 -->
			<result name="success" type="stream">
				<!-- 指定被下载文件的文件类型(此处为后缀为.docx的word文档) -->
				<param name="contentType">application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
				<!-- 指定由getTargetFile()方法被下载文件的inputStream -->
				<param name="inputName">targetFile</param>
				<param name="contentDisposition">filename="test.docx"</param>
				<!-- 指定下载文件缓冲大小 -->
				<param name="bufferSize">4096</param>
			</result>
		</action>


struts2文件下载

标签:struts2

原文地址:http://blog.csdn.net/u011768325/article/details/45366303

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!