1.在html中添加超链接 (要下载的文件是固定的)
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" />
</div>
<div>
<input type="submit" value="文件上传" />
</div>
<div>
<a href="/download?filename=.project">文件下载</a>
</div>
</form>
</body>
2.创建FiledownController
@RestController
public class FileDownloadController {
@RequestMapping("download")
public ResponseEntity<byte []> download(HttpServletRequest request, HttpServletResponse response,String filename) throws Exception{
String path = request.getServletContext().getRealPath("/upload/");
System.out.println("@@@"+path);
File file = new File(path + File.separator + filename);
System.out.println("###"+file);
if(file.exists()){
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attachment:filename="+ URLEncoder.encode(filename,"UTF-8"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //输入流
OutputStream os = null; //输出流
BufferedInputStream bis = null; //缓冲流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1){
os.write(buffer);
i = bis.read(buffer);
}
}catch (Exception e){
e.printStackTrace();
}
try {
bis.close();
fis.close();
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
}