1

我是 Servlet 的新手,并遵循 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();
  }

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

4

1 回答 1

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();
}
于 2012-09-17T07:24:13.297 回答