Reputation: 6815
I wrote a file download servlet and registered in web.xml as below.
<servlet>
<servlet-name>downloadFile</servlet-name>
<servlet-class>com.hibu.HibuProspector.FileDwonloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downloadFile</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
public class FileDownloadServlet extends HttpServlet{
private static final int BYTES_DOWNLOAD = 1024;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException{
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition",
"attachment;filename=SampleFile.xlsx");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/SampleFile.xlsx");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
I have a link in html page as below. on click of the link i need to get the file downloaded.
<a class="button right" target="_blank">Download</a>
Now how can I link the download servlet with the anchor?
Any suggestions?
Upvotes: 0
Views: 3668
Reputation: 11
Everything is correct in all three answers EXCEPT href="/downloadFile" Omit the '/' to produce- href="downloadFile" Worked for me.
Upvotes: 0
Reputation: 2189
It is not good practice to give the root mapping of the web application to do specific operations, therefore update your web.xml with proper servlet mapping as follows:-
<servlet-mapping>
<servlet-name>fileDownload</servlet-name>
<url-pattern>/fileDownload</url-pattern>
</servlet-mapping>
then update the anchor tag with new mapping as below. (you should mention the url-pattern insde the href attribute of the anchor tag.)
<a class="button right" target="_blank" href="/fileDownload">Download</a>
This should work!!!
Upvotes: 1
Reputation: 49372
Change your mapping to something specific:
<servlet-mapping>
<servlet-name>downloadFile</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
And specify the href
attribute of a
tag :
<a class="button right" target="_blank" href="/download">Download</a>
You can read the specs of the anchor#href tag :
This attribute specifies the location of a Web resource, thus defining a link between the current element (the source anchor) and the destination anchor defined by this attribute.
Upvotes: 0
Reputation: 121998
Give proper mapping in web.xml
<servlet-mapping>
<servlet-name>downloadFile</servlet-name>
<url-pattern>/downloadFile</url-pattern>
</servlet-mapping>
You just have to call the servlet through your anchor
<a href="/downloadFile" class="button right" target="_blank">Download</a>
Upvotes: 0