Java uses spring for file download

Source: Internet
Author: User

Today is my first blog post, hope to write something to let everyone see understand, welcome to my message.

HTML page:

<a href= "#" onclick= "DownLoad ()" class= "DownLoad" > Downloads </a>

I used Ajax like a request sent in the background:

/** File Download */
function DownLoad () {
window.open (global_param.context_name+ '/upload/fileddown ');//Here I use Ajax to implement a call to the background method.
}

Then the background is specifically implemented as follows:

/**
* File Download
*/
@Transactional
@Override
Public String Filedown (httpservletresponse response,httpservletrequest request) throws Exception {
String ProjectPath = Request.getservletcontext (). Getrealpath ("/");//Gets the root directory of the project
String path = projectpath+ "/resources/execl/give distribution. xlsx";//Get to the location of the file exec table, this address is the file path you need to download, can be written in your own case
File File=new file (path);//Create File Object
String encoderstr = Urlencoder.encode (File.getname (), "UTF-8");//Turn character
Response.setheader ("Content-disposition", "attachment;filename=\", "+encoderstr +" \ "");//Such conversion can be avoided when the download is Chinese characters
Response.AddHeader ("Content-length", "" "+ File.length ());
Response.setcontenttype ("application/x-msdownload;");
Response.setcharacterencoding ("UTF-8");
OutputStream outputstream = new Bufferedoutputstream (Response.getoutputstream ());
InputStream InputStream = new FileInputStream (file);
byte[] buffer = new byte[1024];
int i =-1;
while ((i = inputstream.read (buffer))! =-1) {
Outputstream.write (buffer, 0, I);
}
Outputstream.flush ();
Outputstream.close (); Closing file streams is critical
Return "Success";
}

Finally finished, hope to help everyone!

Java uses spring for file download

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.