##文件的上传:
@RequestMapping("/upload")
//@RequestParam(“upload”)是表单中name属性,上传的文件封装到了CommonsMultipartFile file里
public String show2(@RequestParam(“upload”) CommonsMultipartFile file,HttpSession session) throws Exception {
System.out.println(file.getContentType()); //文件类型
System.out.println(file.getOriginalFilename()); //文件名
System.out.println(file.getSize()); //文件大小
System.out.println(file.getName()); //表单中文件所在的框的name属性的名称,其实就是@RequestParam(“upload”)
String filename = file.getOriginalFilename();//获取文件名称
//确定上传的路径
String realPath = session.getServletContext().getRealPath("/upload" );
//创建文件上传的目录(或者说是文件夹)
File uploadPath = new File(realPath);
if(!uploadPath.exists()){
//判断如果这个文件夹不存在,就立即新建一个
uploadPath.mkdirs();
}
//确认最终的路径:文件夹+文件名
uploadPath = new File(uploadPath + "/" + filename);
//开始上传
file.transferTo(uploadPath);
return "success";
}
##文件的下载:
//注意,rest风格会默认忽略扩展名(a标签问号传值不会出现这个问题),解决办法是后面加上:.+
@RequestMapping("/download/{f_name:.+}")
public ResponseEntity show(@PathVariable String f_name, HttpSession session) throws Exception{
System.out.println(f_name);
//1.获取文件的真实路径
String realPath = session.getServletContext().getRealPath("/download/" + f_name);
//2.把文件读到程序中
InputStream io = new FileInputStream(realPath); //输入流管道
byte[] body = new byte[io.available()]; //装字节的桶,将读的文件字节流存进去
io.read(body);
//3.创建响应头,给浏览器
//创建的这个响应头是springMVC内部提供的
HttpHeaders httpHeaders = new HttpHeaders();
//文件名为中文时,需要编码,否则下载的时候没有名称
f_name = URLEncoder.encode(f_name, "UTF-8");
//给响应头添加信息,Content-Disposition是固定的,attachment告诉浏览器是附件,
httpHeaders.add("Content-Disposition","attachment;filename="+f_name);
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, HttpStatus.OK);
return responseEntity;
}