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 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() {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;
            //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.setContentLength((int) mp3.length());                        
            FileInputStream input = new FileInputStream(mp3);
            buf = new BufferedInputStream(input);
            int readBytes = 0;    
            while((readBytes = != -1)
       } catch (IOException ioe){       
          throw new ServletException(ioe.getMessage());           
       } finally {
           if(stream != null)
           if(buf != null)

Put the following in your web.xml



* 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';