@RequestMapping( value = "download",method = RequestMethod.GET)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
File file = new File("C:\\Users\\lenovo\\Desktop\\timg.jpg");
String[]fileType=file.getName().split("\\.");
Map map=new HashMap();
map.put("jpg", "image/jpeg;");
map.put("xls", "application/x-xls;");
map.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;");
map.put("doc", "application/msword;");
map.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document;");
map.put("txt", "text/plain;");
try {
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.setCharacterEncoding("UTF-8");
response.setContentType(map.get(fileType[fileType.length-1])+" charset=utf-8");
OutputStream outputStream = response.getOutputStream();
outputStream.write(bytes); //也可以使用
outputStream.close();
outputStream.flush();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ps:mime类型可自行百度