java实现word、pdf文件下载功能

      在SpringMVC的开发过程中,有时需要实现文档的下载功能。文档的下载功能涉及到了java IO流操作的基础知识,下面本文详细介绍java如何实现后台文档下载功能。

      首先根据文档在项目中的存储路径建立File对象,并获取文档的名称和后缀。判断浏览器类型,防止中文文件名出现乱码。

                File file=new File(path);
		String fileName=file.getName();
		String ext=fileName.substring(fileName.lastIndexOf(".")+1);
		String agent=(String)request.getHeader("USER-AGENT"); //判断浏览器类型
		try {  
        	if(agent!=null && agent.indexOf("Fireforx")!=-1) {
        		fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");   //UTF-8编码,防止输出文件名乱码
        	}
        	else {
        		fileName=URLEncoder.encode(fileName,"UTF-8");
        	}
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }

       之后,初始化读入字节流和读出字节流,并设置响应response的输出属性。

        BufferedInputStream bis=null;
        OutputStream os=null;
	response.reset();
    	response.setCharacterEncoding("utf-8"); 
    	if(ext=="docx") {
    		response.setContentType("application/msword"); // word格式
    	}else if(ext=="pdf") {
    		response.setContentType("application/pdf"); // word格式
    	}  
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

       接着调用inputStream和outputStream的read、write函数进行IO流读写操作。最后在写出操作完成后,一定要关闭输出流。

      try {
	        bis=new BufferedInputStream(new FileInputStream(file));
		byte[] b=new byte[bis.available()+1000];
		int i=0;
        	os = response.getOutputStream();   //直接下载导出
        	while((i=bis.read(b))!=-1) {
        		os.write(b, 0, i);
        	}
            os.flush();
            os.close();
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally {
        	if(os!=null) {
        		try {
			     os.close();
			} catch (IOException e) {
			     e.printStackTrace();
				}
        	}
        }
          这样就可以使用java完成word、pdf文档的下载功能。
  • 11
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值