Article updated on

Servlet example that forces an mp3 to be downloaded, not to be played

Sometimes we may need to use a servlet to download mp3 files or other files not to play them or reproduce them. Most browsers understand the application/force-download content type header which does the trick.

package com.web.mypackage.servlet;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Mp3Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Mp3Servlet() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
        try{                 
            //my mp3 path to file
            String pathToFile = "C:/java/workspace/Audio/WebContent/beep.mp3";                       
            stream = response.getOutputStream();
            File mp3 = new File(pathToFile);                           
            //header to force download
            response.setContentType("application/force-download");        
            response.setContentLength((int) mp3.length());                        
            FileInputStream input = new FileInputStream(mp3);
            buf = new BufferedInputStream(input);
            int readBytes = 0;    
            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();
       }     
    }
}

Put the following in your web.xml

  <servlet>
    <servlet-name>Mp3Download</servlet-name>
    <servlet-class>com.web.mypackage.servlet.Mp3Servlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Mp3Download</servlet-name>
    <url-pattern>/test.mp3</url-pattern>
  </servlet-mapping>
 

 

* As this example do not support the response header Accept-Ranges ,  If your connection is stopped while downloading, it won't be able to resume it.

Now your mp3 is ready to be downloaded at  http://yourlocalhost:8080/Yourcontext/test.mp3, you can reference with html link or you can use a javascript function like this one:

function downloadFile(){		
	input_box=confirm("Download file, Are you sure?" );
	if (input_box==true){  
		window.location.href = 'test.mp3';	
	}
}