简体   繁体   English

保存文件对话框未出现

[英]Save file dialog not appearing

I am tryig to make a song available for download on my website. 我是tryig,可以在我的网站上下载一首歌曲。 I am using a download servlet that I have used before to make zip files available for download. 我使用的下载servlet是我以前用来使zip文件可供下载的。 I have run through the code and everything appears to be working, the output stream reads the entire file but the save dialog box does not appear. 我已经遍历了代码,并且一切似乎都可以正常工作,输出流读取了整个文件,但没有出现“保存”对话框。 Any ideas? 有任何想法吗? Thanks for your help. 谢谢你的帮助。 Code is as follows: 代码如下:

  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());
    }
}

Called using: 调用使用:

    dojo.xhrGet(
{
    url: "/downloadSong?song="+item.title[0]
});

You cannot download files by ajax. 您不能通过ajax下载文件。 JavaScript has due to security reasons no facility to spawn a Save As dialogue nor to store them in disk. 由于安全原因,JavaScript无法产生“ 另存为”对话框或将其存储在磁盘中。 It will consume the response, but it can't do anything sensible with it. 它会消耗响应,但无法做任何明智的事情。

You need to use window.location instead: 您需要改用window.location

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

Thanks to the Content-Disposition: attachment header, it won't affect the currently opened page. 多亏了Content-Disposition: attachment标头,它不会影响当前打开的页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM