The Java web project implementation file downloads the instance code
- 2020-04-01 02:20:45
- OfStack
File file = new File(path);//Path is spliced by log path and file name
String filename = file.getName();//Gets the log file name
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
//Remove the Spaces in the file name, and then convert the file name to utf-8, which is used to automatically display the file name in the browser's download box
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);//The output file
os.flush();
os.close();
In struts2.0, you can use the method public void downloadFile(){}, return the value type void, and when called, directly write downloadfile.do to appear the download prompt