Explaining here how I did it:
1. Add following snippet in web.xml:
<pre><code>
<servlet>
<servlet-name>MyDownloadServlet</servlet-name>
<servlet-class>com.lokur.MyDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyDownloadServlet</servlet-name>
<url-pattern>*.download</url-pattern>
</servlet-mapping>
</pre></code>
2. Add following in your servlet:
public class MyDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
//Set the headers.
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=downloaded_horse.mp3");
//TODO: pull the file path from the request parameters
InputStream fileIn = getServletContext().getResourceAsStream("mp3/horse.mp3");
ServletOutputStream outstream = response.getOutputStream();
byte[] outputByte = new byte[40096];
while(fileIn.read(outputByte, 0, 40096) != -1)
{
outstream.write(outputByte, 0, 40096);
}
fileIn.close();
outstream.flush();
outstream.close();
}
}
3. Finally this is the requested jsp:
<pre> <code>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
%>
<body>
<form action="getMusicFile.download" method="post">
Wanna download? <input type="submit" value="Download music">
</form>
</body>
That's all to it!
Cheers,
Akshay :)