1 Packagecom.charmyin.cmstudio.common.utils;2 3 ImportJava.io.BufferedInputStream;4 ImportJava.io.BufferedOutputStream;5 ImportJava.io.File;6 ImportJava.io.FileInputStream;7 Importjava.io.IOException;8 ImportJava.io.InputStream;9 ImportJava.io.OutputStream;Ten One ImportJavax.servlet.http.HttpServletResponse; A - Public classDownloadexcelutil { - the - Public Static voiddownLoadFile (String filePath, httpservletresponse response, String fileName, string fileType) - throwsException { -File File =NewFile (FilePath);//get file files based on file path + //Set the file type (this setting is more than just the next Excel file, one at a stroke) - if("PDF". Equals (FileType)) { +Response.setcontenttype ("APPLICATION/PDF;CHARSET=GBK"); A}Else if("XLS". Equals (FileType)) { atResponse.setcontenttype ("APPLICATION/MSEXCEL;CHARSET=GBK"); -}Else if("Doc". Equals (FileType)) { -Response.setcontenttype ("APPLICATION/MSWORD;CHARSET=GBK"); - } - //file name -Response.setheader ("Content-disposition", "attachment;filename=\" " in+NewString (Filename.getbytes (), "iso8859-1") + "\" "); -Response.setcontentlength ((int) file.length ()); to byte[] buffer =New byte[4096];//buffers +Bufferedoutputstream output =NULL; -Bufferedinputstream input =NULL; the Try { *Output =NewBufferedoutputstream (Response.getoutputstream ()); $input =NewBufferedinputstream (Newfileinputstream (file));Panax Notoginseng intn =-1; - //Traverse, start download the while((n = input.read (buffer, 0, 4096)) >-1) { +Output.write (buffer, 0, n); A } theOutput.flush ();//no less +Response.flushbuffer ();//no less -}Catch(Exception e) { $ //Abnormal self capture $}finally { - //Close the stream, no less - if(Input! =NULL) the input.close (); - if(Output! =NULL)Wuyi output.close (); the } - } Wu - Public Statichttpservletresponse Download (String path, httpservletresponse response) { About Try { $ //Path refers to the paths of the files you want to download. -File File =NewFile (path); - //gets the file name. -String filename =file.getname (); A //gets the suffix name of the file. +String ext = filename.substring (Filename.lastindexof (".") + 1). toUpperCase (); the - //download the file in the form of a stream. $InputStream FIS =NewBufferedinputstream (NewFileInputStream (path)); the byte[] buffer =New byte[Fis.available ()]; the fis.read (buffer); the fis.close (); the //Empty Response - Response.reset (); in //set the header of the response theResponse.AddHeader ("Content-disposition", "attachment;filename=" +NewString (Filename.getbytes ())); theResponse.AddHeader ("Content-length", "" "+file.length ()); AboutOutputStream toclient =NewBufferedoutputstream (Response.getoutputstream ()); theResponse.setcontenttype ("Application/octet-stream"); the toclient.write (buffer); the Toclient.flush (); + toclient.close (); -}Catch(IOException ex) { the ex.printstacktrace ();Bayi } the returnresponse; the } -}
Java Download sample