(10)Struts2文件下载

Struts2中的文件下载与在Servlet中下载相似,来回顾一下在Servlet中进行文件下载:

	String realpath = ServletActionContext.getServletContext().getRealPath("/download");
		
		try {
			
			FileInputStream fis = new FileInputStream(new File(realpath ,"test.txt");
			//设置文件类型
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment;filename="+newUser.getFilename());
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];

			int len;
			
			while ((len=fis.read(b))!=-1) {
				os.write(b, 0, len);
			}
			os.flush();
			fis.close();
			
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}


 

在Struts2中进行下载:

 

 

Action中:

public String download() throws Exception {
		String id = ServletActionContext.getRequest().getParameter("id");
		User newUser = userService.queryById(id);
		String path = newUser.getPath();
		String fileName = newUser.getFileName();
		File file = new File(path, fileName);
		FileInputStream fis = new FileInputStream(file);
		newUser.setIs(fis);
		ActionContext.getContext().getValueStack().push(newUser);
		return "download";
	}


 

struts.xml中:

<result name="download" type="stream">
				<!-- 对应web中下载配置:application/x-msdownload -->
				<param name="contentType">application/x-msdownload</param>
				<param name="inputName">is</param>
				<!-- 对应web中下载配置:response.setHeader("Content-Disposition", "attachment;filename="+newUser.ge					tFilename()); -->
				<param name="contentDisposition">attachment;filename=${fileName}</param>
				<!-- 对应web中下载配置:byte[] b = new byte[1024]; -->
				<param name="bufferSize">1024</param>
				</result>


总结:从以上两段代码中不难看出,Struts2中的文件下载只不过是将一些设置放在配置文件中了,文件下载与上传的关键之处就在于准确 的获取文件所在的路径,如果上传或下载的文件名称中带有中文,则需要谨慎处理。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值