保存文件对话框未显示

时间:2011-10-23 19:24:40

标签: java javascript servlets download

我试着在我的网站上下载一首歌。我正在使用我之前使用的下载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]
});

1 个答案:

答案 0 :(得分:1)

您无法通过ajax下载文件。由于安全原因,JavaScript无法生成另存为对话框,也无法将它们存储在磁盘中。它将消耗响应,但它无法做任何明智的事情。

您需要使用window.location代替:

window.location = "/downloadSong?song=" + item.title[0];

感谢Content-Disposition: attachment标题,它不会影响当前打开的页面。