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