When doing web development, often have such a function, such as export into Excel, PDF, TXT, etc., will read the data to be exported, and then generate temporary files, and then call a downloaded subroutine. Now let's talk about how to write this download subroutine.
The first generation of temporary files must be a temporary path of the tmpfilename, and then we download is the need for filename filename, next paste I wrote this subroutine source code:
public static void DownloadFile (String fileName, String tmpfilename, HttpServletRequest request, HttpServletResponse
Response) throws IOException {if (Stringutils.isempty (fileName) && stringutils.isempty (tmpfilename)) {return;
File File = new file (tmpfilename);
if (!file.exists ()) {return;
String postfix = tmpfilename.substring (Tmpfilename.lastindexof ("."));
Response.reset ();
String useragent = Request.getheader ("user-agent"); if (Useragent.contains ("MSIE") | | | useragent.contains ("Trident")) {Response.setheader ("content-disposition", "
Attachment;filename=\ "" + urlencoder.encode (filename, "utf-8") + postfix+ ""); else {filename = new String (filename.getbytes ("Utf-8"), "iso-8859-1");//download file name display encoding processing response.setheader ("Content
-disposition "," attachment;filename=\ "" + filename + postfix+ "" ");
} response.setcontenttype ("Application/x-msdownload;charset=utf-8");
FileInputStream fis = new FileInputStream (file); Bufferedoutputstream BOS = new Bufferedoutputstream (Response.getoutputstream ());
byte[] buffer = new byte[2048];
int readlength = 0;
while ((Readlength = fis.read (buffer))!=-1) {bos.write (buffer,0,readlength);
try {fis.close ();
catch (IOException e) {} try {Bos.flush ();
Bos.close (); catch (IOException e) {}}Call this program, when you want to download the file will pop a box, select the path to download can save the file to the local.