Struts – download file from website example

To let user download a file from your Struts web project, you have to inform “HttpServletResponse” to return an application file instead of the normal HTML page.


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

In server side, you can get the download file from 3 different ways

1. File system

Get it from file system


FileInputStream in = 
  new FileInputStream(new File("C:\\filename.zip"));
2. Project web path

Assume your file is located at “http://yourname.com/StrutsExample/upload/filename.zip“, and the “StrutsExample” is your project name (serlvet context).


//jndi:/yourname.com/StrutsExample/upload/filename.zip
URL url = getServlet().getServletContext().getResource("upload/filename.zip");
InputStream in = url.openStream();
3. Bytes array

If you retrieve the files or blob data from database, it’s usually return as bytes array.


byte[] bytes = new byte[4096];
InputStream in = new ByteArrayInputStream(bytes);
Download this Struts download file example – Struts-Download-File-Example.zip

1. Action class

An action class to return an application file instead of the normal HTML page, and get the “superfish.zip” file for user to download.


package com.mkyong.common.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DownloadFileAction extends Action{
	
   @Override
   public ActionForward execute(ActionMapping mapping, ActionForm form,
     HttpServletRequest request, HttpServletResponse response)
     throws Exception {
		
     //return an application file instead of html page
     response.setContentType("application/octet-stream");
     response.setHeader("Content-Disposition","attachment;filename=superfish.zip");
        
     try 
     {
       	//Get it from file system
       	FileInputStream in = 
      		new FileInputStream(new File("C:\\superfish.zip"));
        	
        //Get it from web path
        //jndi:/localhost/StrutsExample/upload/superfish.zip
        //URL url = getServlet().getServletContext()
        //               .getResource("upload/superfish.zip");
        //InputStream in = url.openStream();
        	
        //Get it from bytes array
        //byte[] bytes = new byte[4096];
        //InputStream in = new ByteArrayInputStream(bytes);

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

     }catch(Exception e){
    	e.printStackTrace();
   }

   return null;
  }
}

2. JSP Page

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>





Download file from server - 
struts-tutorial.zip 
	


3. struts-config.xml

Struts configuration file.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>
	
		<action
			path="/DownloadPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/display.jsp"/>
		
		<action
			path="/DownloadIt"
			type="com.mkyong.common.action.DownloadFileAction"
			>
		</action>
		
	</action-mappings>

</struts-config>

4. Test it

http://localhost:8080/StrutsExample/DownloadPage.do

struts-download-file-example1

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
Arne
Guest
Arne

Very nice article; helped me a long way. Thanks

Yolanda Olmedo Canabal
Guest
Yolanda Olmedo Canabal

Excelente Post!! funciona de maravilla. Gracias!

prince
Guest
prince

hi sir i want to store a file in database and i want to retrieve the stored file from the database and the i should get listed all the stored file from the database and among those i should select any one and the selected file should get downloaded in my local machine i want to do it in struts please provide me solution for this….

sriram
Guest
sriram

Sir,
iam using struts 1.x and i tried the code here for downloading the file,i write the same code in Struts action class.after that file is downloading properly,but it is not forwarding to another page.i write the code at the end as return mapping.findForward(“someText”);

and in struts-config.xml file i mention the path associated with this name sir.but it is not forwarding

Kane
Guest
Kane
Hi , I have tried this code . I am picking up Excel file from path on disk . It only works with Firefox, chrome , safari but has problem with IE 8 . Please help with any suggestion . My code snippet : String disHeader = “attachment; filename=”; ServletOutputStream opstream = response.getOutputStream(); response.setContentType( “application/x-excel” ); response.setHeader( “content-disposition”,disHeader+ fileName ); byte[] buf = new byte[4096]; while( (length=fileToDownload.read(buf,0,4096)) != -1 ) { //byte[] defaultBytes = (new String(buf)).getBytes(“GBK”); // String newEncodingStr = new String(defaultBytes, “UTF-8”); opstream.write(buf,0,length); } fileToDownload.close(); opstream.flush(); opstream.close();
Amita Mirajkar
Guest
Amita Mirajkar

any luck?

mahesh
Guest
mahesh

How to retrieve a file from database based on search content in struts

Godfray
Guest
Godfray

how can i refresh the jsp page again?
if i use
return mapping.findForward(“success”);
instead of
return null;,
it gives error that response already….

Vipin
Guest
Vipin

Sir Your Code was very Good….
it really Works Well.

Thanks a lot Sir.

Shalini
Guest
Shalini

Sir i wann to know that how i implement autocomplete off in html tag in struts please answer it.

Siddharth Mehta
Guest
Siddharth Mehta

how can i extend this code to run in struts 2?

candida
Guest
candida

I am glad to find so various helpful information here within the post, we need develop additional techniques in this regard, thanks for sharing

Best Man Gifts
Guest
Best Man Gifts

Best Man Gifts

As a man, you score to permit, you most likely possess never been just at shopping, or justified likeable shopping for that entity. Now that you’re achievement to be married, you’ll feat that choosing gifts for your optimum man bonk turn voice of your to-do itemise. It’s a stimulating task, but if you see where to looking, you’ll be fit to feat the perfect sharing in no abstraction.

free manga download
Guest
free manga download

http://freemanga4u2.blogspot.com A neater examine Marvel comics online for free?

trackback
Struts 2 download file example
trackback
how to buy Xanax online without a prescription, buy Xanax with no … | Rx Drugs Blog

[…] Struts – download file from website example | Struts […]