How to Download File via Response (Example Code)

Here is an example code for you to use Response to download files.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1.Get the file path
    String realPath = "D:\\project\\\servlet-main\\\\response\\\src\\\main\\\resources\\\\avatar.jpg";
    // 2. Get the file name
    String fileName = realPath.substring(realPath.lastIndexOf("\\\") + 1);
    // 3. Set the request header (Content-Disposition of the header to support file download)
    resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    // 4. Get the input stream of the downloaded file: FileInputStream
    FileInputStream inputStream = new FileInputStream(realPath);
    // 5. Create buffer
    int length = 0;
    byte[] buffer = new byte[1024];
    // 6. Get the input stream object: OutputStream
    ServletOutputStream outputStream = resp.getOutputStream();
    // 7. Write the stream to the buffer and use the OutputStream to output the data in the buffer to the client
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *