文件的上传
public String file(MultipartFile multipartFile){
if (multipartFile == null){
return "文件为空";
}
//获取文件的原名称 getOriginalFilename
String OriginalFilename = multipartFile.getOriginalFilename();
//获取时间戳和文件的扩展名,拼接成一个全新的文件名; 用时间戳来命名是为了避免文件名冲突
String fileName = UUID.randomUUID()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);
//定义文件存放路径
/* String filePath = "D:\\Java\\IDEAwenjian\\discexcel\\src\\main\\resources\\fiel\\";*/
String filePath = "/home/xiaokai/disshangchuan/";
//新建一个目录(文件夹)
File dest = new File(filePath+fileName);
//判断filePath目录是否存在,如不存在,就新建一个
if (!dest.getParentFile().canExecute()){
dest.getParentFile().mkdirs(); //新建一个目录
}
try {
//文件输出
multipartFile.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
String filePath2 = filePath+fileName;
return filePath2;
}
文件下载
@GetMapping("/file")
public ResponseEntity<byte[]> doReport(String fileName) {
try {
File file = new File(fileName);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",
new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 获取文件的字节数组 - 需要使用commons-io依赖包
byte[] content = FileUtils.readFileToByteArray(file);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}