【蜕变之路】第36天 算法题之一 (2019年3月26日)

    Hello,大家好!我是程序员阿飞!今天我们主要学习一下:如何使用java实现在线查看或者下载文件

    //文件在线下载或在线查看

    public void downLoad(String filePath,HttpServletResponse response,boolean isOnLine){

      File f = new File(filePath);

      //判断文件是否存在

      if(!f.exists){

        response.sendError(404,"File not found");

        return;

      }

      //将文件读入文件流

      BufferInputSrtream br = new BufferInputSrtream(new FileInputStream(f));

      byte[] buf = new byte[1024];

      int len = 0;

      //重置响应头

      response.reset();

      if(isOnLine){

        URL u = new URL("file:///"+filePath);

        response.setContentType(u.openConnection().getContentType());//告知浏览器文件直接打开

        response.setHeader("Content-Disposition","inline;filename="+f.getName());//设置文件的名称

      }else{

        response.setContentType("application/x-msdownload");//告知浏览器文件直接下载

        response.setHeader("Content-Disposition","attachment;filename="+f.getName());//设置文件的名称

      }

      OutputStream out = response.getOutputStream();

      while((len=br.read(buf))>0){

        out.write(buf,0,len);

        br.close();

        out.close();

      }

    }

    参考网址:https://blog.csdn.net/qiushuang_0425/article/details/79559255



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章