JAVA文件下载

本文介绍了一个使用Java实现的文件下载方法,通过设置HTTP响应头来指定下载文件类型为Excel,并处理了文件读取及输出流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    //文件下载
    public static String downloadFile(File file) {
            HttpServletResponse response = ServletActionContext.getResponse();
            FileInputStream fis = null;
            BufferedInputStream buff = null;
            OutputStream out = null;
            try {
               /* 如果文件存在 */
               if (file.exists()) {
                   //设置为没有缓存
                   response.reset();
                   //设置response的编码方式
                   //response.setContentType("application/x-download");  
                   response.setContentType("application/ms-excel"); //这一句更细化,告诉浏览器要下载的是excel文件
                   //设置下载文件名
                   response.setHeader("Content-Disposition", "filename="+new String(file.getName().getBytes(),"UTF-8"));
                   //读出文件到i/o流
                   fis=new FileInputStream(file);
                   buff=new BufferedInputStream(fis);
                   //从response对象中得到输出流,准备下载
                   out = response.getOutputStream();
                   //PrintWriter out = response.getWriter();随便哪句都可以
                   //以字节的方式写入内容
                   int i;   
                   while((i = buff.read()) != -1){     
                       out.write(i);
                   }
                   //把内容全部推到文档里
                   out.flush();   
               }else{
                   return "download fail";//文件不存在
               }
           } catch (Exception e) {
            // TODO: handle exception
           }finally{
               try {
                   if (buff != null)  
                       buff.close();      
                   if (out != null)  
                       out.close();     
               } catch (IOException e) {
                   return "download fail";
               }
           }
        return "download success";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值