First, the front door through a tag to open the interface, incoming file ID
<a href= "/cdc/announcement/downloadfile/1" > Download </a>
Second, the backstage receives the ID, looks for the correspondence file, carries on the downloading
@RequestMapping (value = "Downloadfile/{id}", method = Requestmethod.get)
@PreAuthorize ("hasauthority (' View ')")
@ResponseBody public
void DownloadFile (HttpServletRequest req, HttpServletResponse resp, @PathVariable ("id" Long ID) {
announcementannex Announcementannex = Announcementannexservice.selectbyid (ID);
Real filename
String name = Announcementannex.getannexurl ();
String downloadname=announcementannex.getannexname ();
The file name after the transcoding, used to download the filename
publiccontroller.download (resp,name,downloadname);
}
which download method
/** * @param resp * @param name file real name * @param downloadname file Download when the names */public static Voi
D Download (HttpServletResponse resp, string name, String downloadname) {string fileName = null;
try {fileName = new String (downloadname.getbytes ("GBK"), "iso-8859-1");
catch (Unsupportedencodingexception e) {e.printstacktrace (); }///home/tomcat/apache-tomcat-9.0.1/files String Realpath = "D:" + file.separator + apache-tomcat-8.5.15
"+ File.separator +" files "; String realpath=file.separator+ "Home" +file.separator+ "Tomcat" +file.separator+ "apache-tomcat-9.0.1" +
file.separator+ "Files";
String Path = realpath + file.separator + name;
File File = new file (path);
Resp.reset ();
Resp.setcontenttype ("Application/octet-stream");
Resp.setcharacterencoding ("Utf-8");
Resp.setcontentlength ((int) file.length ()); Resp.setheader ("Content-dispOsition "," attachment;filename= "+ filename);
byte[] buff = new byte[1024];
Bufferedinputstream bis = null;
OutputStream OS = null;
try {os = Resp.getoutputstream ();
bis = new Bufferedinputstream (new FileInputStream (file));
int i = 0;
while ((i = bis.read (buff))!=-1) {os.write (buff, 0, i);
Os.flush ();
} catch (IOException e) {e.printstacktrace ();
Finally {try {bis.close ();
catch (IOException e) {e.printstacktrace (); }
}
}
FileName is the name after the file is downloaded, filepath is the folder address where the file is located, path is the file address, note the response type and encoding method set
Where File.separator is a path delimiter, he can automatically identify which operating system is using a different path delimiter (Windows is ' \ ', Linux is '/').