@RequestMapping("download")
public ResponseEntity<byte[]> downLoad(HttpServletRequest req) throws IOException {
//返回一个响应实体
//指定文件的路径
String path = req.getServletContext().getRealPath("/uploadFile") + "/3ae8e408-218b-4851-928c-073a5fa0adeb.jpg";
//创建响应的头信息对象
HttpHeaders head = new HttpHeaders();
//标记以流的方式做出响应
head.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//以附件的形式响应给用户
head.setContentDispositionFormData("attachment", URLEncoder.encode("3ae8e408-218b-4851-928c-073a5fa0adeb.jpg","utf-8"));
File file = new File(path);
ResponseEntity<byte[]> en = new ResponseEntity<>(FileUtils.readFileToByteArray(file),head, HttpStatus.CREATED);
return en;
}
@RequestMapping("upload")
public String upload(@RequestParam("myFile") MultipartFile myFile, HttpServletRequest req) throws IOException {
//获取文件的原始名称tomcat.jpg
String originalFilename = myFile.getOriginalFilename();
//实际开发当中,都要将文件重新命名进行存储
//根据我们的实际名称,获取到源文件的后缀,涉及到,字符串的截取,lastIndexOf(".")获取到.下表的索引值
String fileName = UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));
System.out.println(fileName);
//文件册存储的路径
String realpath = req.getServletContext().getRealPath("/uploadFile")+"/";
myFile.transferTo(new File(realpath+fileName));
//这个才是文件上传到真正指定的位置
System.out.println("上传成功:"+realpath+fileName);
return "ok";
}
07-04
591
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-31
1734
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)