Java WEB file download

Source: Internet
Author: User

Java WEB file download

Now we want to use the springMVC-based file download function.

Is not effective

Where is the problem?

After clicking the link, if it is a text file, it will be automatically opened instead of downloaded. If it is an image, it will be opened rather than downloaded.

So what should we do? After research, File Download is actually a request that uses response to download files.

The following is an example of object download in the form of a binary stream.

/*** Download file */@ RequestMapping (value = downLoadFile) public void downLoadFile (ReimFjInfo reimFjInfo, HttpServletRequest request, HttpServletResponse response) {log.info (download file ); // download the file as a binary stream. try {String fileName = new String (request. getParameter (fjName ). getBytes (ISO-8859-1), UTF-8); // get File information File downFile = new File (reimFjInfo. getFjUrl (); // get the object's byte input stream InputStream bufferStream = new BufferedInputStream (new FileInputStream (downFile); byte [] buffer = new byte [bufferStream. available ()]; bufferStream. read (buffer); bufferStream. close (); response. reset (); // set the response Header. You need to set the file name, which is the file name response displayed when downloading the file. setHeader (Content-disposition, attachment; filename = + new String (fileName. getBytes (gb2312), ISO8859-1); // when you are not sure about the file type, contentType uses the following form, which is. * (binary stream, unknown download file type) response. setContentType (application/octet-stream); // get the response byte output stream OutputStream out = new BufferedOutputStream (response. getOutputStream (); out. write (buffer); out. flush (); out. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}

 

 

 

Related Article

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.