Struts2实现文件的下载

直接看代码:

下载
文件入口:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Insert title here</title>
</head>
<body>
    <a href="download.action?fileName=<%=java.net.URLEncoder.encode("测试用的RAR.rar","utf-8").toString()
                .replace("%","_")%>">测试用的Rar.rar文件</a>
    <a href="download.action?fileName=abc.rar">abc.rar</a>
</body>
</html>

下载的action:

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

import org.apache.struts2.ServletActionContext;

/**
 * 实现文件下载的action
 * @author acer
 *
 */
public class DownLoad {

	private String fileName = "";

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public InputStream getDownloadFile() throws Exception {
		fileName = fileName.replace("_", "%");
		fileName = URLDecoder.decode(fileName, "utf-8");
		System.out.println(fileName);
		ServletActionContext.getResponse().setContentType("application/x-msdownload");
		FileInputStream fis = new FileInputStream(new File(
				ServletActionContext.getRequest().getRealPath("\\upload")+"\\"+fileName));
		fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
		
		ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+fileName);
		
		return fis;
	}
	
	public String execute(){
		return "success";
	}
}

配置文件:

<action name="download" class="DownLoad">
	<result name="success" type="stream">
		<param name="inputName">downloadFile</param>
		<param name="bufferSize">1000000</param>
	</result>
</action>

这样就可以实现文件的下载了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值