ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.URLEncoder;ImportJavax.servlet.http.HttpServletResponse;Importorg.springframework.util.StringUtils;/*** File Download*/ Public classFileload {/*** Return file stream using response*/ Public voidLoadFile (String filePath, httpservletresponse response) {//declaring tool classesBufferedinputstream in =NULL; Bufferedoutputstream out=NULL; Try { //if the path is empty if(Stringutils.isempty (FilePath)) {Throw NewException ("Invalid filepath of NULL."); } //no files found .File File =NewFile (FilePath); if(!file.exists ()) { Throw NewException ("File not exist in path [" + FilePath + "]"); } //Get file nameString FileName =File.getname (); //output file stream to browserin =NewBufferedinputstream (NewFileInputStream (FilePath)); out=NewBufferedoutputstream (Response.getoutputstream ()); Response.setcontenttype ("Application/x-download;charset=utf-8"); Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (filename, "UTF-8")); byte[] buffer =New byte[8192]; intCount = 0; while((count = in.read (buffer, 0, 8192))! =-1) {out.write (buffer,0, Count); } out.flush (); File=NULL; } Catch(Exception e) {e.printstacktrace (); } finally{Closestream (in, out); } } /*** Turn off the input/output stream*/ Public voidClosestream (InputStream in, outputstream out) {if(NULL!=In ) { Try{in.close (); } Catch(IOException e) {//e.printstacktrace (); } } if(NULL!=Out ) { Try{out.close (); } Catch(IOException e) {//e.printstacktrace (); } } }}
HttpServletResponse Implementing File Download