我需要实现文件下载。我不想给任何服务器端文件的url直接下载。我创建了一个servlet,它将打开文件并将其写入响应流。现在来到前面gwt我有onResponseReceived(请求请求, Response response) 收到响应时会调用哪个。现在如何进一步进行?.我需要的操作是,流中的文件应该下载到客户端计算机。
有人可以帮我解决这个问题吗?
您可以使用 _blank、_parent、_top、_self 中的任何一个
你试过了Window.open(ServletUrl, "_parent", "location=no")
吗?
并尝试在“application/exe”的响应中设置 ContentType
这将提示用户保存或运行。
小服务程序代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8");
File file = new File("/path/to/files", filename);
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
response.setHeader("Content-Length", file.length());
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
}