直接在controller层添加下载接口,代码如下:
//fileName、filePath也可以作为参数传入
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "a.txt";// 设置文件名
if (fileName != null) {
//设置文件路径
String realPath = "D:" + File.separator + "a_agentd.conf";
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名和编码格式
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
InetAddress addr = InetAddress.getLocalHost();
String ip=addr.getHostAddress(); //获取本机ip
replacTextContent(ip);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}