文件下载

本文介绍如何在JavaWeb及Struts2框架中实现文件下载功能,包括使用ServletActionContext获取文件路径、设置HTTP响应头以解决中文文件名乱码问题,并通过InputStream与OutputStream完成文件内容的读取与输出。

对应文件上传的下载

1、javaweb方法实现:

	public String download(){
		try {
			//获取文件ID
			String fileID = elecUser.getFileID();
			//使用文件ID,查询用户文件列表,获取路径path
			ElecUserFile elecUserFile = this.elecUserService.findUserFileByID(fileID);
			String fileURL = elecUserFile.getFileURL();//相对路径
			String path = ServletActionContext.getServletContext().getRealPath("")+fileURL;
			
			//获取文件名称
			String filename = elecUserFile.getFileName();
			//为防止中文乱码,重新编码
			filename = new String(filename.getBytes("gbk"), "iso8859-1");
			
			//填写下载文件的头部信息
//			response.setContentType("application/vnd.ms-excel");//多种文件类型,不知道具体的类型,不用写,默认是所有类型
			//setHeader必须写,第一个参数固定写法(内容的处理形式),处理形式有两种情况:(1)inline(内联)点击直接用浏览器打开;(2)附件,可以指定文件名
			response.setHeader("Content-disposition", "attachment;filename="+filename);
			
			//使用路径path,查找到对应的文件,转换成InputStream
			InputStream in = new FileInputStream(new File(path));
			//从响应对象response中获取输出流OutputStream
			OutputStream out = response.getOutputStream();
			
			//读取输入流的数据到输出流中
//			IOUtils.copy(in, out);//封装好的方法
			//手动读写的方法
			for(int b=-1;(b=in.read())!=-1;){
				out.write(b);
			}
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return NONE;
	}

2、struts2下载方式实现:

2.1、struts-default.xml中的默认实现


2.2、org.apache.struts2.dispatcher.StreamResult类中默认配置:


2.3、struts.xml文件中的配置


2.4、action中方法实现:

      注意:

      1)需要将filename放入到request域,可以在struts.xml中通过${#request.filename}获取

      2)不需要写OutputStream,但是需要将InputStream于对象关联,可以在struts.xml中通过<param name="inputName">inputStream</param>获取

	/**
	 * struts2方式实现文件下载
	 * @return
	 */
	public String download(){
		try {
			//获取文件ID
			String fileID = elecUser.getFileID();
			//使用文件ID,查询用户文件列表,获取路径path
			ElecUserFile elecUserFile = this.elecUserService.findUserFileByID(fileID);
			String fileURL = elecUserFile.getFileURL();//相对路径
			String path = ServletActionContext.getServletContext().getRealPath("")+fileURL;
			
			//获取文件名称
			String filename = elecUserFile.getFileName();
			//为防止中文乱码,重新编码
			filename = new String(filename.getBytes("gbk"), "iso8859-1");
			request.setAttribute("filename", filename);
			
			//使用路径path,查找到对应的文件,转换成InputStream
			InputStream in = new FileInputStream(new File(path));

			//与栈顶的InputStream关联
			elecUser.setInputStream(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "download";
	}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值