How to download file from website- Java / Jsp

Here i show a simple java example to demonstrate how to let user download a file from website. No matter you are using struts , JSP, Spring or whatever other java framework, the logic is same.

1) First we have to set HttpServletResponse response to tell browser about system going to return an application file instead of normal html page


response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv");

we can also specified a download file name in attachment;filename=, above example export a csv file name “downloadfilename.csv” for user download.

2) There have 2 ways to let user download a file from website

Read file from physical location


File file = new File("C:\\temp\\downloadfilename.csv");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();

byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
	out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();

Export database data or string directly to InputStream for user download.


StringBuffer sb = new StringBuffer("whatever string you like");
InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
ServletOutputStream out = response.getOutputStream();

byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
	out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();

3) Done

Here i show my struts example to demonstrate how to directly write data into InputStream and output it as “temp.cvs” to let user download.


public ActionForward export(ActionMapping mapping, ActionForm form,
	HttpServletRequest request, HttpServletResponse response)
	throws Exception {
				
	//tell browser program going to return an application file 
        //instead of html page
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=temp.csv");
				
	try 
	{
		ServletOutputStream out = response.getOutputStream();
		StringBuffer sb = generateCsvFileBuffer();
					
		InputStream in = 
                    new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
					
		byte[] outputByte = new byte[4096];
		//copy binary contect to output stream
		while(in.read(outputByte, 0, 4096) != -1)
		{
			out.write(outputByte, 0, 4096);
		}
		in.close();
		out.flush();
		out.close();
					
	  }
	  return null;
	}

private static StringBuffer generateCsvFileBuffer()
{
	StringBuffer writer = new StringBuffer();

	writer.append("DisplayName");
	writer.append(',');
	writer.append("Age");
	writer.append(',');
	writer.append("HandPhone");
	writer.append('\n');

        writer.append("mkyong");
	writer.append(',');
	writer.append("26");
	writer.append(',');
	writer.append("0123456789");
	writer.append('\n');
			
	return writer;
}

Here’s a file download example in Servlet code

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Nayana
Guest
Nayana

I have stored excel file as BLOB. On click of filename in the JSP user should be able to retrieve the BLOB and display it in the excel. Could you please help me here?

Anamika
Guest
Anamika

I am also looking to learn java can you share any website where I can learn it properly.

Al
Guest
Al

Excellent, simple and to the point. You do a great job, MK.

Nitin
Guest
Nitin

Hi,

I am having issue while downloading the large set of data. it showing “Your browser sent a request that this server could not understand.” i am using below code …

byte[] bytes = getBytes();

response.setContentType(“application/vnd.ms-excel”);

response.setHeader(“Content-disposition”, “attachment;filename=export.xlsx”);

OutputStream out = response.getOutputStream();

out.write(bytes);

out.flush();

out.close();

SudhaVelan
Guest
SudhaVelan
Hi I m trying to save the return string as zip file.But the file is stored as encoded. Response header : Content-Disposition: attachment; filename=”filename.extension” Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/octet-stream I tried to read as follow : InputStream input = response.getEntityInputStream(); byte[] buffer = new byte[4096]; int n = – 1; OutputStream output = new FileOutputStream( file ); while ( (n = input.read(buffer)) != -1) { if (n > 0) { output.write(buffer, 0, n); } } But the file is saved as encoded. Can you please suggest any thing else? Its a zip file
Chris
Guest
Chris

Did you find a fix for this?

rohit
Guest
rohit

i am getting junk data along with csv while downloading from screen.the junk data is source page of jsp

naresh
Guest
naresh

how you get it solved

Rajeswar
Guest
Rajeswar

Hi same here. Did you manage to solve it?

Chris
Guest
Chris

I am getting the right response, but I cannot tell where the file is being downloaded to. I don’t get any kind of save dialog from the browser. Where is the download supposed to go?

KyungHwan Min
Guest
KyungHwan Min

I just want to leave one comment. If you download xlsx Excel file, writing codes in JSP will result in file corruption. Writing download logic in servlet is working from my experiment.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType(“text/html”);
String filename = request.getParameter(“filename”);
//System.out.println(“Filename = ” + filename);
response.setContentType(“application/octet-stream”);
response.setHeader(“Content-Disposition”,”attachment;filename=”+filename);
String basePath = “/root/sub_path”;
File file= new File(basePath+”/”+filename);
System.out.println(“Filename = ” + basePath+”/”+filename);
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream sos = response.getOutputStream();

byte[] outputByte = new byte[4096];

while(fileIn.read(outputByte, 0, 4096) != -1 )
{
sos.write(outputByte , 0, 4096);
}
fileIn.close();
sos.flush();
sos.close();
}

Ahmed
Guest
Ahmed

Hallo,

Can you explain how can i download files with Apache Wicket?

Thanx!

Soheb
Guest
Soheb
Soheb
Guest
Soheb
I am using JSF and in one of the managed bean (view scope) i have a method as: public String viewReport() { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setContentType(“application/vnd.ms-excel”); response.setHeader(“Content-Disposition”,”attachment;filename=book1.xls”); try { File file = new File(“C:\\soheb\\book1.xls”); FileInputStream fileIn = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); byte[] outputByte = new byte[4096]; //copy binary contect to output stream while(fileIn.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } fileIn.close(); out.flush(); out.close(); } catch(IOException e) { e.printStackTrace(); } return null; } The excel which is getting retrieved is corrupted file. It has some strange characters above and below is the entire code of… Read more »
sudha
Guest
sudha

your website is so useful

sunil yadav
Guest
sunil yadav

best site for technical interview question………………….

Sudeep Nayak
Guest
Sudeep Nayak

The root post worked for me. And it was really helpful.
I just lost 3 days to download a zip file.

You code really rocks.

Thanks and keep sharing.

_
Guest
_

Whats up are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own.
Do you need any html coding expertise to make your own blog?
Any help would be really appreciated!

trackback
Struts 2 download file example
Jia Bin
Guest
Jia Bin

Hi, is this possible to do this in struts 2? Thanks…

Enrico Bergamo
Guest
Enrico Bergamo
Hello, I’m having the same problem as Nayana here. My files are stored in a BLOB field in DB2. I’m trying to retrieve them, but I only have success for text files, but we need to retrieve DOC, PDF and XLS as well. Considering they are stored base64 encoded, I’m using the following code to download the file, but as I said before, just worked on text files <%@ page import="java.io.*"%> <%@ page import="com.ibm.misc.*"%> <% String fileName = request.getParameter("fileName"); String fileType = request.getParameter("fileType"); String fileContent = b64Decode(request.getParameter("fileContent"));//Blob content response.setContentType(fileType); //response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); response.setContentLength((int) fileContent.length()); try {… Read more »
sara
Guest
sara

hello sir,
i want clear code for downloading files in jsp

Rodney
Guest
Rodney

Oh This Works All Fine, But I Want To Download A Password Protected File From The Net Like In Firefox When The URL is Entered It Prompts A Password Box To Download The File.

With This Code So Far I Get Errors As The Web Host Gives Access Denied.

¿ I Want [Yeah I Demand] A Code in That if The File [URL] is Password Protected It Will Tell You To Enter The Password And Then Download The File if Password is Correct?

Thank-You BTW

Gabe T.
Guest
Gabe T.

Thank you so very very much for sharing your solution online :D!
Exactly what I was looking for.
Much appreciated, sir :)!

trackback
Programming anxiety

[…] How to download file from website- Java / Jsp […]

Nikhil
Guest
Nikhil

Hi,

I am using

response.setContentType(“application/octet-stream”);
response.setHeader(“Content-Disposition”, “attachment;filename=” + outfile.getName());

It ends up downloading my jsp page in test format.

Please help.

Thanks & Regards,
Nikhil

webcom
Guest
webcom

response.setContentType(“application/octet-stream”);
response.setHeader(“Content-Disposition”, “attachment;filename=” + outfile.getName());

The great thing i discovered is you actually dont need to specify the application type in order to open downloaded file. Since outfile.getName() parameter contains the file extension (myfile.txt, myfile.doc…), any file type can be downloaded with this Content type declaration
I tried this with Word, PDF, XLS, JPG, MPG, ZIP they all work with “application/octet-strea” with no problem

Sunaina
Guest
Sunaina

I want to learn java please tell me any website where I can learn it.

Tomino
Guest
Tomino

Hi,

I did it this way. It works great in Mozilla and IE7 and bellow. But same code doesn’t work in IE8. When executing out.flush() or out.close(), the browser gets closed with no exception thrown. Does anybody have an idea what is wrong?

I tried content type “application/octet-stream”, “application/force-download” as well as “application/vnd.ms-excel”, cause I download an excel file.

Shashank
Guest
Shashank

Hi,

I modified the above code to download a word document. Below are the changes –

response.setContentType(“application/doc”);
response.setHeader(“Content-disposition”,”attachment; filename=Wordfile.doc”);

The document downloads fine. But when I open the document in MSWord, I get the below error –

“Word Cannot Start the Converter MSWRD632.WPC”

After clicking the OK button a couple of times the documents opens up fine. Please let me how to fix this issue.

Roshan
Guest
Roshan

Thanks very much… you save my time…you have release my stress..Thanks again..god bless u..

Pochacco
Guest
Pochacco

Hi, I’m a little confused as to where I put these codes into.
Sorry I’m not so good with html stuff.

Sibyl Cocoran
Guest
Sibyl Cocoran

hi-ya, great post.

mahesh
Guest
mahesh

very useful content dude

Haja
Guest
Haja

while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}

change this code to

int byteRead;
while((byteRead = in.read(outputByte, 0, 4096)) != -1)
{
out.write(outputByte, 0, byteRead );
}

Onymakris
Guest
Onymakris

Great article. Thanks.

Gachugu
Guest
Gachugu

Excellent! And this addition was very nice too… otherwise the download appends bytes to make the chunk 4096! Good work guys.

trackback
Servlet code to download the text file – Java | Servlet

[…] Here’s another file download example in Struts […]

Ronnie
Guest
Ronnie

From my web layer i pass an id value, then a type value(string), and two ate values….
Actually i useed an Http service and sent these parameters using send() method to the EJB…