servlet simple implementation of the file download method

  • 2020-05-26 08:34:31
  • OfStack

This article illustrates how servlet can simply be downloaded. I will share it with you for your reference as follows:


public static void download(String path, HttpServletResponse response) {
  try {
    // path The path of the file you want to download. 
    File file = new File(path);
    //  Get the file name. 
    String filename = file.getName();
    //  Gets the suffix name of the file. 
    String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
    //  Download files as a stream. 
    InputStream fis = new BufferedInputStream(new FileInputStream(path));
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    //  empty response
    response.reset();
    //  Set up the response the Header
    response.addHeader("Content-Disposition", "attachment;filename="
        + new String(filename.getBytes()));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream toClient = new BufferedOutputStream(
        response.getOutputStream());
    response.setContentType("application/octet-stream");
    toClient.write(buffer);
    toClient.flush();
    toClient.close();
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}

I hope this article has been helpful to you in java programming.


Related articles: