Search code examples
javahttpserver

HttpExchange send file


I am using my server to distribute some files (in a zip), however, I want the user to enter a CAPTCHA before being able to download the file.

This presents a new problem, because the code:

    private void sendFileResponse(final String filename, byte[] response, HttpExchange httpExchange) {
        //<editor-fold defaultstate="collapsed" desc="code">
        if (response != null && response.length > 0 && httpExchange != null) {
            try {
                httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/zip");
                
                OutputStream outputStream = httpExchange.getResponseBody();
                httpExchange.sendResponseHeaders(200, response.length);
                outputStream.write(response);
                outputStream.flush();
                outputStream.close();
                httpExchange.getRequestBody().close();
            } catch (Exception e) {
                System.out.println(Misc.getStackTrace(e));
            }
        }
        //</editor-fold>
    }

... will cause the file to be named as the download request webpage's URL. For example, if a user enters the correct CAPTCHA and downloads the file at /download.html, the file they receive would be download.html, not my file's name.

How do I make the server send the file as the file's name and cause the webpage to refresh at the same time?


Solution

  • Use the Content-Disposition HTTP header field:

    Content-Disposition: attachment; filename=yourfilename

    httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=" + filename);