[英]Save file dialog not appearing
我是tryig,可以在我的网站上下载一首歌曲。 我使用的下载servlet是我以前用来使zip文件可供下载的。 我已经遍历了代码,并且一切似乎都可以正常工作,输出流读取了整个文件,但没有出现“保存”对话框。 有任何想法吗? 谢谢你的帮助。 代码如下:
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
:
window.location = "/downloadSong?song=" + item.title[0];
多亏了Content-Disposition: attachment
标头,它不会影响当前打开的页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.