This article describes the simple method of servlet to implement file download. Share it for your reference, as follows:
public static void download(String path, HttpServletResponse response) { try { // path refers to the path of the file to be downloaded. File file = new File(path); // Get the file name. String filename = file.getName(); // Get the suffix name of the file. String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // Download the file in the form of a stream. InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // Clear response response response.reset(); // Set the response's 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 will be helpful to everyone's Java programming.