文件下载:
@RequestMapping("/download")
public ResponseEntity<byte []> download(HttpSession session){
//获得当前项目
ServletContext application = session.getServletContext();
InputStream in = application.getResourceAsStream("/static/video/文件名.mp4");
byte[] body;
try {
body = new byte[in.available()];
//读取文件数据
in.read(body);
//关流
in.close();
HttpHeaders headers = new HttpHeaders();
//告诉浏览器下载内容的信息 下载内容的格式
headers.add("Context-Type",application.getMimeType("/static/video/文件名.mp4"));
headers.add("Content-Disposition","attachment; filename=11-书城第三阶段-注册.mp4");
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body,headers,HttpStatus.OK);
//返回entity对象
return responseEntity;
} catch (IOException e) {
e.printStackTrace();
}
//如果下载失败 返回一个null
return null;
}
文件上传:
@RequestMapping(value="/upload")
public String upload(String username,MultipartFile photo) {
System.out.println("username");
try {
photo.transferTo(new File("e:\\image\\"+photo.getOriginalFilename()));
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return "upload_success";
}
原文地址:https://www.cnblogs.com/m-ming/p/11679972.html