<div onclick="downMap('12-1P11Q51458.jpg')">下载地图</div>
function downMap(fileName) {
window.location.href = "/download?fileName=" + fileName;
}
@RequestMapping(value = "/download", method = { RequestMethod.POST, RequestMethod.GET })
public void download(HttpServletResponse response, @RequestParam("fileName") String fileName) {
response.setHeader("content-type", "image/png");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
String realPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath() + "/img/map/";
bis = new BufferedInputStream(new FileInputStream(new File(realPath + fileName)));
int read = bis.read(buff);
while (read != -1) {
outputStream.write(buff, 0, buff.length);
outputStream.flush();
read = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
参考文章https://www.cnblogs.com/kzyuan/p/12493993.html