Java File Download function implementation __java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.