我正在尝试使用 ajax 和 servlet 下载文件,但我得到的最大结果是成功获取文件 parseado
我有 servlet 的这一部分:
else if(type.equals("downloadDocument")){
String file = request.getParameter("filePath");
File f = new File(file);
if (f.exists() && f.isFile()){
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(f);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > -1){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
那个电话:
$.ajax({
type : "POST",
url : "./ServletDocuWindow?downloadDocument",
data : datos,
success : function(r) {
}
});
最佳答案
我没有从 AJAX 下载文件,而是在新的单独窗口上传递请求。然后,我的 servlet 被调用,文件被下载到我的本地。此外,当文件开始下载时,新窗口将关闭
我想您需要添加以下代码,然后就可以开始了。
response.setContentType("application/octet-stream");
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", AppUtility.getConvertedString(fileName)); //to ensure that there are no space in the file name
response.setHeader(headerKey, headerValue);
关于javascript - 使用Java Servlet下载动态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43389188/