1, a hyperlink to the page, link to the controller
<href= "<%=path%>/download"> Click to download file </a >
2, the controller in the code:
@RequestMapping ("/download") @ResponseBody publicvoidthrows Exception { // get Download road excelandcsvdownload.downloadfile (Moban.csv,csv, Download, response);//pass in the file name, file format, path, response parameter } that need to be downloaded sequentially
3, Tool class:
PackageCom.common.util;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJavax.servlet.http.HttpServletResponse; Public classexcelandcsvdownload{ Public Static BooleandownLoadFile (String name,string type,string path,httpservletresponse response)throwsException {String fileName=name; String FileType=type; File File=NewFile (Path+filename);//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"); }Else if("CSV". Equals (FileType)) {Response.setcontenttype ("APPLICATION/MSEXCEL;CHARSET=GBK"); }Else if("Doc". Equals (FileType)) {Response.setcontenttype ("APPLICATION/MSWORD;CHARSET=GBK"); }Else if("XLS". Equals (FileType)) {Response.setcontenttype ("APPLICATION/MSEXCEL;CHARSET=GBK"); } //file nameResponse.setheader ("Content-disposition", "attachment;filename=\" "+NewString (Filename.getbytes (), "iso8859-1") + "\" "); Response.setcontentlength ((int) file.length ()); byte[] buffer =New byte[4096];//buffersBufferedoutputstream output =NULL; Bufferedinputstream input=NULL; Try{Output=NewBufferedoutputstream (Response.getoutputstream ()); Input=NewBufferedinputstream (Newfileinputstream (file)); intn =-1; //Traverse, start download while((n = input.read (buffer, 0, 4096)) >-1) {output.write (buffer,0, N); } output.flush (); //no lessResponse.flushbuffer ();//no less}Catch(Exception e) {//Abnormal self capture}finally { //Close the stream, no less if(Input! =NULL) Input.close (); if(Output! =NULL) Output.close (); } return false; }}
Springmvc java File download