Java with IO output stream for file download!

Source: Internet
Author: User

Using IO output streaming: Directly on Java code,

HTML interface only needs a <a href= "xxxxx/xxx/xx" > Download </a> address directly write the corresponding Java address just fine.

Method One:

	@RequestMapping ("domload.it") public
	void Domload (httpservletresponse response, HttpServletRequest request) Throws IOException  {
		 //GET request filename 
		String path = Request.getservletcontext (). Getrealpath ("/resource/pdf/ Enquiry.pdf ");
		SYSTEM.OUT.PRINTLN (path);
		To download the way to open
		Response.setheader ("Content-disposition", "attachment;filename=java.pdf");
		File File = new file (path);
		FileInputStream FIS =  new FileInputStream (file);
		Write
		 Servletoutputstream out = Response.getoutputstream ();
		Define read buffer
		byte buffer[] = new byte[1024];
		Define read length
		int len = 1024;
		Loop read while
		(len = fis.read (buffer))!=-1) {
			out.write (Buffer,0,len);
		}
		
		Releasing Resources
		Fis.close ();
		Out.flush ();
		Out.close ();
	}	
	
Method 2:
	
	@RequestMapping ("domload1.it") public
	void Domload1 (httpservletresponse response, HttpServletRequest Request) throws IOException  {
		 //get requested filename 
		String path = Request.getservletcontext (). Getrealpath ("/ Resource/pdf/enquiry.pdf ");
		SYSTEM.OUT.PRINTLN (path);
		File File = new file (path);
		Open Response.setheader by Download
		("Content-disposition", "Attachment;filename=" +urlencoder.encode (file.getName) , "UTF-8"));
		
		Create Liu Object
		filereader reader = new FileReader (file);
		Write
		PrintWriter out = Response.getwriter ();
		Define read buffer
		char buffer[] = new char[1024];
		Define read length
		int len = 1024;
		Loop read while
		(len = reader.read (buffer))!=-1) {
			out.write (Buffer,0,len);
		}
		
		Releasing Resources
		Reader.close ();
		Out.flush ();
		Out.close ();
		
	}	


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.