没有出现保存文件对话框

Save file dialog not appearing

本文关键字:保存文件 对话框      更新时间:2023-09-26

我想在我的网站上下载一首歌曲。我正在使用以前使用过的下载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头,它不会影响当前打开的页面