Java “保存文件”对话框未出现
我想在我的网站上下载一首歌。我正在使用一个下载servlet,我以前使用过它来提供zip文件供下载。我已经运行了代码,一切都正常,输出流读取整个文件,但没有显示“保存”对话框。有什么想法吗?谢谢你的帮助。代码如下:Java “保存文件”对话框未出现,java,javascript,servlets,download,Java,Javascript,Servlets,Download,我想在我的网站上下载一首歌。我正在使用一个下载servlet,我以前使用过它来提供zip文件供下载。我已经运行了代码,一切都正常,输出流读取整个文件,但没有显示“保存”对话框。有什么想法吗?谢谢你的帮助。代码如下: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String son
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String song = request.getParameter("song");
StringBuilder filePath = new StringBuilder();
try {
Thread.sleep(1);
String[] info = getSongInfo(song);
filePath.append("D:\\My Music\\My Song.m4a");
File file = new File(filePath.toString());
if (!file.exists()) {
throw new FileNotFoundException(file.getAbsolutePath());
}
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Type", "audio/mp4a-latm");
response.setHeader("Content-disposition", "attachment; filename="+song+".m4a");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[4096];
while (true) {
int length = bis.read(buf);
if (length == -1) {
break;
}
bos.write(buf, 0, length);
}
bos.flush();
bos.close();
bis.close();
} catch (InterruptedException e) {
System.err.println("Error message: " + e.getMessage());
}
}
调用时使用:
dojo.xhrGet(
{
url: "/downloadSong?song="+item.title[0]
});
您不能通过ajax下载文件。由于安全原因,JavaScript没有生成另存为对话框或将其存储在磁盘中的功能。它将消耗响应,但它不能用它做任何明智的事情 您需要使用
窗口。位置
:
window.location = "/downloadSong?song=" + item.title[0];
由于
内容配置:附件标题,它不会影响当前打开的页面。您无法通过ajax下载文件。由于安全原因,JavaScript没有生成另存为对话框或将其存储在磁盘中的功能。它将消耗响应,但它不能用它做任何明智的事情
您需要使用窗口。位置
:
window.location = "/downloadSong?song=" + item.title[0];
由于内容处理:附件标题,它不会影响当前打开的页面。在新窗口中打开指向该文件的链接在新窗口中打开指向该文件的链接谢谢,100%修复了我的问题。谢谢,100%修复了我的问题。