两个接口由于时间关系,都是按照最简单的方式编写,还有很多问题,但文件的处理方式没有问题。
1.文件上传
文件上传,使用表单方式上传 MultipartFile multipartFile 参数 后端就收到文件,存储到指定的文件夹下,并进行重命名
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
public void uploadFileTest(MultipartFile multipartFile) throws Exception{
String orgFile = multipartFile.getOriginalFilename();
String fileName = UUID.randomUUID().toString().replace("-","")+orgFile.substring(orgFile.lastIndexOf("."));
Path path = Paths.get("D:/resFile/".concat(fileName));
if (Files.notExists(path)){
path = Files.createFile(path);
}
Long s = Files.copy(multipartFile.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件大小为:"+s);
}
2.文件下载
文件下载,浏览器传递文件名或者路径到后台接口,后台根据路径将文件下载。
@GetMapping(value = "/downFile")
public void downFileTest(
@RequestParam(name = "fileName")String fileName, HttpServletResponse response) throws Exception{
String filePath = "D:/resFile/";
String contentType = Files.probeContentType(Paths.get(filePath));
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
File file = new File(filePath+fileName);
FileChannel inChannel = null;
WritableByteChannel outChannel = null;
outChannel = Channels.newChannel(response.getOutputStream());
inChannel = new FileInputStream(file).getChannel();
inChannel.transferTo(0,inChannel.size(),outChannel);
inChannel.close();
}