[ Team LiB ] Previous Section Next Section

Recipe 13.4 Sending an Audio File


You want to send an audio file such as an MPEG layer 3 (MP3) media type.


Use a java.io.BufferedInputStream to fetch the audio data, and the javax.servlet.ServletOutputStream from the javax.servlet.http.HttpServletResponse object to send the data to the client.


The code in Example 13-4 uses the same approach as the prior recipes, except for the MIME type, which is specified as audio/mpeg.

Web browsers associate a number of other MIME types for MP3 files, including audio/x-mpeg, audio/mp3, and audio/x-mp3.

The user requests a filename in the URL, as in:


The deployment descriptor (web.xml) maps the servlet path /sendmp3 to the servlet class of Example 13-4: com.jspservletcookbook.SendMp3. If the requested file does not already have the .mp3 suffix, then the code adds that file extension. A context-param element in the deployment descriptor specifies the directory where the audio files are kept:


Example 13-4 uses this directory name, plus the filename, as the constructor parameter to create a new java.io.File object, which is the source for a java.io.FileInputStream. A BufferedInputStream buffers the bytes from the song file, which the ServletOutputStream response reads.

Example 13-4. Sending an MP3 file
package com.jspservletcookbook;           

import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

public class SendMp3 extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException {
        //get the filename from the "file" parameter
        String fileName = (String) request.getParameter("file");
        if (fileName == null || fileName.equals(""))
            throw new ServletException(
            "Invalid or non-existent file parameter in SendMp3 servlet.");
        // add the .mp3 suffix if it doesn't already exist
        if (fileName.indexOf(".mp3") == -1)
           fileName = fileName + ".mp3";
        //where are MP3 files kept?
        String mp3Dir = getServletContext( ).getInitParameter("mp3-dir");

        if (mp3Dir == null || mp3Dir.equals(""))
            throw new ServletException(
            "Invalid or non-existent mp3-Dir context-param.");
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
            stream = response.getOutputStream( );
            File mp3 = new File(mp3Dir + "/" + fileName);
            //set response headers
            "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)

        } catch (IOException ioe){
            throw new ServletException(ioe.getMessage( ));
        } finally {
            //close the input/output streams
            if(stream != null)
                stream.close( );

            if(buf != null)
                buf.close( );

  } //doGet
  public void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException {

Review Recipe 13.1 for a further explanation of this code, including the warning at the end of the "Discussion" section about logged exceptions that may occur with Internet Explorer.

See Also

Recipe 13.1 on MIME types and sending a PDF file as binary data; Recipe 13.2 and Recipe 13.3 on sending Word and XML files, respectively, as binary data; Recipe 13.5 on receiving an input stream representing a web resource such as web.xml; the RFC technical documents on MIME: ftp://ftp.rfc-editor.org/in-notes/rfc2045.txt and ftp://ftp.rfc-editor.org/in-notes/rfc2046.txt; RFC 2183 at ftp://ftp.rfc-editor.org/in-notes/rfc2183.txt for background information on the Content-Disposition header; the Media Types section of the HTTP Pocket Reference by Clinton Wong (O'Reilly); Chapter 1 introducing the development of a servlet.

    [ Team LiB ] Previous Section Next Section