abhithakur88
abhithakur88

Reputation: 407

Writing mp3 file to response output stream

I am new to Servlets and following Headfirst. It has an example to download jar file with mime type "application/jar". I changed it to "audio/mpeg3" to download an mp3 file. I get the player on the browser but it doesn't play. Here is the code:

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

Can someone please help to figure out the problem?

Upvotes: 1

Views: 7325

Answers (1)

MaVRoSCy
MaVRoSCy

Reputation: 17859

you can try out something like this

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

Upvotes: 6

Related Questions