@RequestMapping("/download")
public String downloads(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//要下载的图片地址
String path = req.getServletContext().getRealPath("/upload");
String fileName="微信图片_20230308194233.jpg";
//1.设置response 响应头
resp.reset();//设置页面不缓存,清空buffer
resp.setCharacterEncoding("UTF-8");
resp.setContentType("multipart/form-data");//二进制传输数据
//设置响应头
resp.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
File file = new File(path, fileName);
//2、读取文件--输入流
InputStream is = new FileInputStream(file);
//3、写出文件 --输出流
OutputStream out = resp.getOutputStream();
byte[] buff =new byte[1024];
int index;
//4.执行写出操作
while ((index=is.read(buff))!=-1){
out.write(buff,0,index);
out.flush();
}
out.close();
is.close();
return "redirect:/index.jsp";
}