Asynchronous File Downloader in Java and Javascript.

Hi All,

I had a requirement where I had to use Ajax based file downloader. I  tried alot but couldn't find anywhere.

Finally I got one solution which is similar to the Ajax in some ways.

I have implemented it using an iframe in html and it worked really great for me. I thought I can share this with you guys.

I hope this will be useful for some one.

I have one servlet which is used to download file:

package com.pawan;  

import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import javax.servlet.ServletContext;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

public class ServletDownloadDemo extends HttpServlet{  

 private static final int BYTES_DOWNLOAD = 1024;  

 public void doGet(HttpServletRequest request,  
 HttpServletResponse response) throws IOException{  
 response.setContentType("text/plain");  
 response.setHeader("Content-Disposition",  
 "attachment;filename=downloadname.txt");  
 ServletContext ctx = getServletContext();  
 InputStream is = ctx.getResourceAsStream("/testing.txt");  

 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();  
 }  
}

Here is the web.xml for this

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>serlvetdemo</display-name>

 <servlet>
 <servlet-name>ServletName</servlet-name>
 <servlet-class>com.pawan.ServletDownloadDemo</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>ServletName</servlet-name>
 <url-pattern>/DownloadDemo</url-pattern>
 </servlet-mapping>
</web-app>

I have implemented a very simple jsp to test this.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>Insert title here</title>  
<script>

 function downloadFileAsynch(url){
 var elemIF = document.createElement("iframe");
 elemIF.name="testing";
 elemIF.src = url;
 elemIF.style.display = "none";
 document.body.appendChild(elemIF);
 }
</script>

</head>  
<body>  
<input type="button" value="download" onclick="downloadFileAsynch('DownloadDemo');"/>  
<p> select me and then download</p>  
</body>  
</html>  

It does work very well. I have tested it. Let me know your feed back and how it works.

Share on : Twitter, Facebook or Google+