Mevan
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
Java
@RestController
@RequestMapping( value = "/file")
public class FileController {
@PostMapping( value="/upload")
public FileInfo upload(MultipartFile file) throws IllegalStateException, IOException {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename()); //文件原始名
System.out.println(file.getSize());
String folder = "D:\\Program Files\\Java\\eclipse\\javaProject\\spring-security\\spring-security-demo\\src\\main\\resources\\upload";
File localFile = new File(folder, new Date().getTime() + file.getOriginalFilename());
file.transferTo(localFile); //将上传的文件写到本地的文件中
return new FileInfo(localFile.getAbsolutePath());
}
@GetMapping( value="/download")
public void download(@RequestParam(value = "path" , required = true , defaultValue = "1538896688835springboot原理.txt") String path ,HttpServletRequest request
,HttpServletResponse response ) throws Exception {
try (
//JDK 1.7之后,声明在 try() 括号中的流。回自动关闭
InputStream inputStream = new FileInputStream(new File("D:\\Program Files\\Java\\eclipse\\javaProject\\spring-security\\spring-security-demo\\src\\main\\resources\\upload\\"
, path));
OutputStream outputStream = response.getOutputStream();
){
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachmet;filename=fi32.txt");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}
}
}