2011-10-23 20 views
1

私のウェブサイトにダウンロード可能な曲を作成しようとしています。私は以前ダウンロードした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] 
}); 
+0

このファイルへのリンクを別のウィンドウで開きます –

答えて

1

あなたはAJAXでファイルをダウンロードすることはできません。 JavaScriptはセキュリティ上の理由から、名前を付けて保存ダイアログを生成したり、ディスクに保存したりすることができません。それは応答を消費しますが、それで賢明なことはできません。あなたが代わりにwindow.locationを使用する必要が

Content-Disposition: attachmentヘッダーへ

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

おかげで、それが現在開いているページには影響しません。

+0

ありがとうございました。100%問題を修正しました。 – shortspider

+1

ようこそ。 – BalusC

関連する問題