我正在使用我的服务器分发一些文件(在 zip 中),但是,我希望用户在能够下载文件之前输入验证码。
这带来了一个新问题,因为代码:
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>
}
... 将导致文件被命名为下载请求网页的 URL。例如,如果用户输入正确的验证码并在/download.html 下载文件,他们收到的文件将是 download.html,而不是我的文件名。
如何让服务器将文件作为文件名发送,并使网页同时刷新?
最佳答案
使用 Content-Disposition HTTP header 字段:
Content-Disposition:附件;文件名=你的文件名
httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=" + filename);
关于java - HttpExchange 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535254/