Servlets 将mp3文件写入响应输出流

Servlets 将mp3文件写入响应输出流,servlets,Servlets,我对Servlets是个新手,而且我是头一个。它有一个下载mime类型为“application/jar”的jar文件的示例。我把它改为“audio/mpeg3”来下载mp3文件。我在浏览器上看到播放器,但它不播放。代码如下: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCont

我对Servlets是个新手,而且我是头一个。它有一个下载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();
  }

有人能帮你解决这个问题吗?

你可以试试这样的方法

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

你可以试试这样的东西

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