java io 文件下载功能

一.

@RequestMapping(value = "/download/{filename}")

public void downloadFile(HttpServletRequest request,HttpServletResponse response,

@PathVariable(value = "filename") String filename)

throws IOException {

//获取项目路径

String readPath = request.getServletContext().getRealPath("/");

readPath = readPath.substring(0, readPath.lastIndexOf("\"));

readPath = readPath.substring(0, readPath.lastIndexOf("\"));

//文件绝对路径

String picPath = readPath+File.separator+"pai"+File.separator+"attachmentSimple"+File.separator+"1"+File.separator + filename;

File file = new File(picPath);

if(!file.exists()){

throw new RuntimeException("视频文件不存在!");

}

response.setContentType("application/force-download");// 设置强制下载不打开

response.addHeader("Content-Disposition",

"attachment;fileName=" + filename);// 设置文件名

FileInputStream inputStream = new FileInputStream(file);

ServletOutputStream out = response.getOutputStream();

int b = 0;

byte[] buffer = new byte[1024];

while (b != -1){

out.write(buffer,0,b);

b = inputStream.read(buffer);

}

inputStream.close();

out.close();

out.flush();

}

}

二.

@RequestMapping("download")

public void download(@RequestParam("id") String id,

HttpServletRequest request, HttpServletResponse response){

VideoInfo video = (VideoInfo) videoService.getObjectById(VideoInfo.class, id);

String path = request.getServletContext().getRealPath(video.getRestorePath());

File file = new File(path);

if(!file.exists()){

throw new RuntimeException("视频文件不存在!");

}

String fileName = video.getRestorePath().substring(video.getRestorePath().indexOf(File.separator)+1);

response.setContentType("application/force-download");// 设置强制下载不打开

response.addHeader("Content-Disposition",

"attachment;fileName=" + fileName);// 设置文件名

byte[] buffer = new byte[1024];

FileInputStream fis = null;

BufferedInputStream bis = null;

try {

fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);

OutputStream os = response.getOutputStream();

int i = bis.read(buffer);

while (i != -1) {

os.write(buffer, 0, i);

i = bis.read(buffer);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (bis != null) {

try {

bis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (fis != null) {

try {

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

原文地址:https://www.cnblogs.com/zhi-ming/p/10453161.html