簡體   English   中英

保存文件對話框未出現

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM