将mp3文件写入响应输出流

时间:2012-09-17 07:03:49

标签: servlets

我是Servlets的新手并且关注Headfirst。它有一个使用mime类型“application / jar”下载jar文件的示例。我将其更改为“audio / mpeg3”以下载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();
  }

有人可以帮忙解决问题吗?

1 个答案:

答案 0 :(得分:6)

你可以试试这样的东西

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