2012-09-17 50 views
1

我是Servlets和Headfirst的新手。它有一個使用MIME類型「application/jar」下載jar文件的例子。我將其更改爲「audio/mpeg3」以下載mp3文件。我在瀏覽器上看到播放器,但它不播放。這裏是代碼:將mp3文件寫入響應輸出流

public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException 

{ 
    resp.setContentType("audio/mpeg3"); 

    ServletContext ctx=this.getServletContext(); 
    InputStream is=ctx.getResourceAsStream("/RaOne.mp3"); 

    int read=0; 
    byte[] bytes=new byte[1024]; 

    OutputStream os=resp.getOutputStream(); 
    while((read=is.read(bytes))!=-1) 
    { 
     os.write(bytes, 0, read); 
    } 

    os.flush(); 
    os.close(); 
    } 

有人可以幫忙找出問題嗎?

回答

5

你可以嘗試這樣的事情

ServletOutputStream stream = null; 
BufferedInputStream buf = null; 
try { 
    stream = response.getOutputStream(); 
    File mp3 = new File("/myCollectionOfSongs" + "/" + fileName); 

    //set response headers 
    response.setContentType("audio/mpeg"); 

    response.addHeader("Content-Disposition", "attachment; filename=" + fileName); 

    response.setContentLength((int) mp3.length()); 

    FileInputStream input = new FileInputStream(mp3); 
    buf = new BufferedInputStream(input); 
    int readBytes = 0; 
    //read from the file; write to the ServletOutputStream 
    while ((readBytes = buf.read()) != -1) 
    stream.write(readBytes); 
} catch (IOException ioe) { 
    throw new ServletException(ioe.getMessage()); 
} finally { 
    if (stream != null) 
    stream.close(); 
    if (buf != null) 
    buf.close(); 
}