strtus2.0实现文件下载

文件下载需要注意的是中文文件名的问题
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.net.*"
	pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>简单的文件下载</title>
	</head>
	<body>
		<!-- 为了完成文件上传,设置该表单的enctype属性为multipart/form-data。 -->
		<s:form action="download.action" method="post"
			enctype="multipart/form-data" theme="simple">
			<ul>
				<li>
					<s:url id="url" action="download">
						<s:param name="inputPath">/upload/<%=URLEncoder.encode("新建文本文档.txt","utf-8")%>
						</s:param>
						<s:param name="filename"><%=URLEncoder.encode("新建文本文档.txt","utf-8")%>
						</s:param>
					</s:url>
					<s:a href="%{url}">下载jpg</s:a>
					<br>
					<s:url id="url" action="download">
						<s:param name="inputPath">/upload/a.doc
						</s:param>
						<s:param name="filename">a.doc
						</s:param>
					</s:url>
					<s:a href="%{url}">下载doc</s:a>
					<br>
					<s:url id="url" action="download">
						<s:param name="inputPath">/upload/c.wma
						</s:param>
						<s:param name="filename">c.wma
						</s:param>
					</s:url>
					<s:a href="%{url}">下载wma</s:a>
				</li>
			</ul>
		</s:form>
	</body>
</html>

action
package org.login.actions;

import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {
	private String inputPath;

	private String filename;

	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public InputStream getInputStream() throws Exception {
		//服务器上的文件 如/upload/a.txt
		inputPath=URLDecoder.decode(inputPath,"UTF-8");
		InputStream input=ServletActionContext.getServletContext().getResourceAsStream(
				inputPath);
		return input;
		//不在服务器上的文件 如F://a.txt
		//return new java.io.FileInputStream(inputPath);
	}

	public String download() throws Exception {
		//不进行动态设置下载文件名称及路径
		//inputPath = "/image/close_w.gif";// 要下载的文件名称
		//filename = "a.jpg"; // 保存文件时的名称
		return SUCCESS;
	}
}

struts.xml
<action name="download" class="DownloadAction"
			method="download">
			<result name="success" type="stream">
				<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
				<param name="inputName">inputStream</param>
				<param name="bufferSize">4096</param>
				<param name="contentDisposition">
					attachment;filename="${filename}"
				</param>
			</result>
		</action>

你可能感兴趣的:(java,c,jsp,.net,struts)