问题代码:
@RequestMapping(value = "/downloadImage")
public void downloadImage(String fileurl,HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String fileName = URLDecoder.decode(fileurl, "UTF-8");
String suffix = fileName.substring(fileName.lastIndexOf("."));
File file = new File(fileName);// //1.获取要下载的文件的绝对路径
String newDname = "new" + getDate() + suffix; //2.获取要下载的文件名
if (file.exists()) { //判断文件父目录是否存在
response.reset();
response.setHeader("content-type", "application/octet-stream");
response.setContentType("image/jpg");
response.setHeader("Content-Disposition", "attachment;filename=" + newDname); //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
byte[] buff = new byte[1024]; //5.创建数据缓冲区
BufferedInputStream bis = null;
OutputStream os = null;
try {
bis = new BufferedInputStream(new FileInputStream(file)); //4.根据文件路径获取要下载的文件输入流
os = response.getOutputStream(); //6.通过response对象获取OutputStream流
/* int i = bis.read(buff); //7.将FileInputStream流写入到buffer缓冲区
while (i != -1) {
os.write(buff, 0, buff.length); //8.使用将OutputStream缓冲区的数据输出到客户端浏览器
os.flush();
i = bis.read(buff);
}*/
IOUtils.copy(bis,os);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}