4

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?

1
  • I'm sure this is a duplicate, but can't seem to find the original right now... Commented Aug 27, 2014 at 19:21

1 Answer 1

6

Use the Content-Disposition HTTP header field:

Content-Disposition: attachment; filename=yourfilename

httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=" + filename);
Sign up to request clarification or add additional context in comments.

3 Comments

@user3635998 Try using httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=" + filename + ";");
I just got it working with the same thing and have edited your reply. Thank you for your help.
I added the code to the answer. You should always use getRequestHeaders() or getResponseHeaders(). I don't really know what setAttribute() is good for, but the other two sound quite straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.