Struts2文件下载

方法1、在struts中使用servlet下载

public class DownLoadAction extends ActionSupport {
	public String download() throws IOException{
		HttpServletResponse response = ServletActionContext.getResponse();
		String path = ServletActionContext.getRequest().getRealPath("/Download/旅行.jpg");//获得资源绝对路径
		String filename = path.substring(path.lastIndexOf("\\")+1);//获得文件名
        filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码
	//	response.setHeader("content-disposition", "attachment;filename="+filename);//如果资源名称是中文,则应该用URLEncoder转码,设置响应头为文件下载
		response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
		InputStream in = null;
		OutputStream out = null;
		try{
			in = new FileInputStream(path);//读文件
			int len = 0;
			byte []buf = new byte[1024];
			out = response.getOutputStream();
			while((len = in.read(buf)) > 0)
			{
				out.write(buf,0,len);//写入response对象
			}
		}finally{//关闭流
			if(in != null){
				try{
					in.close();
				}catch(Exception e){}
			}
			if(out != null){
				try{
					out.close();
				}catch(Exception e){}
			}
		}
		return null;    //一定要返回null,所以在<action></action>中不用配置result
	}
}


2、使用Response下载

DownLoadResponseAction.java

public class DownLoadResponseAction extends ActionSupport {
//filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
	private String filename;
	@Override
	public String execute() throws Exception {
		filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");//改编码
		System.out.println(filename);
		HttpServletRequest request = ServletActionContext.getRequest();//获得request
		HttpServletResponse response = ServletActionContext.getResponse();//获得response
		String path = request.getRealPath("/DownLoad");//得到资源的路径	
		File file = new File(path+filename);
		response.setCharacterEncoding("UTF-8");
        filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码
		response.setHeader("content-disposition", "attachment;filename="+filename);//设置响应头为文件下载
		response.setContentLength((int)file.length());
		int len = 0;
		byte []buffer = new byte[1024];
		InputStream is = new FileInputStream(file);
		OutputStream os= response.getOutputStream();//向浏览器写数据
		while((len = is.read(buffer)) != -1){
			os.write(buffer,0,len);
		}
		is.close();
		os.close();
		return null;
	}
	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值