我在servlet中创建了一个zip文件。现在我想使用Ajax触发该servlet并提示用户下载对话框。我可以触发servlet,但不知道如何获取保存对话框。我该如何实现这个功能?
你不能使用AJAX下载文件。AJAX的作用是从服务器下载数据供JavaScript处理。
如果要让用户下载文件,可以使用简单的链接到文件/Servlet,或者如果你真的非常需要使用JavaScript,那么可以将URL赋值给document.location.href
。
此外,你需要确保服务器(在这种情况下为Servlet)发送适当的MIME类型,在ZIP文件的情况下,最可能的是application/zip
。
<a href="fileservlet/somefilename.zip">download file</a>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
response.setHeader("Content-Type", getServletContext().getMimeType(fileName));
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
// ...
}
window.location = "fileservlet/somefilename.zip";
如果您实际上使用POST,则可以使用(隐藏的)同步POST表单引用servlet的URL,并让JavaScript对其执行。
function down() {
var url = "/Jad";
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//alert("xmlhttp.status" + xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}
window.location = url;
。 - BalusC
<a href="/path/to/file">下载</a>
将在单击链接时“下载文件”。 - RoToRa