importlombok.extern.slf4j.Slf4j;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;import java.io.*;
@RestController
@RequestMapping(value= "/file")
@Slf4jpublic classFileController {/*** windows下的文件路径*/
private final String File_PATH = "F:/upload/temp";
@PostMapping(value= "/upload")
String uploadFileBufferToLocal(MultipartFile file) {//将文件缓冲到本地
boolean localFile =createLocalFile(File_PATH, file);if(!localFile){
log.error("Create local file failed!");return "Create local file failed!";
}
log.info("Create local file successfully");return "Create local file successfully";
}/*** 通过上传的文件名,缓冲到本地,后面才能解压、验证
*@paramfilePath 临时缓冲到本地的目录
*@paramfile*/
public booleancreateLocalFile(String filePath,MultipartFile file) {
File localFile= newFile(filePath);//先创建目录
localFile.mkdirs();
String originalFilename=file.getOriginalFilename();
String path= filePath+"/"+originalFilename;
log.info("createLocalFile path = {}", path);
localFile= newFile(path);
FileOutputStream fos= null;
InputStream in= null;try{if(localFile.exists()){//如果文件存在删除文件
boolean delete =localFile.delete();if (delete == false){
log.error("Delete exist file "{}" failed!!!",path,new Exception("Delete exist file ""+path+"" failed!!!"));
}
}//创建文件
if(!localFile.exists()){//如果文件不存在,则创建新的文件
localFile.createNewFile();
log.info("Create file successfully,the file is {}",path);
}//创建文件成功后,写入内容到文件里
fos = newFileOutputStream(localFile);
in=file.getInputStream();byte[] bytes = new byte[1024];int len = -1;while((len = in.read(bytes)) != -1) {
fos.write(bytes,0, len);
}
fos.flush();
log.info("Reading uploaded file and buffering to local successfully!");
}catch(FileNotFoundException e) {
e.printStackTrace();return false;
}catch(IOException e) {
e.printStackTrace();return false;
}finally{try{if(fos != null) {
fos.close();
}if(in != null) {
in.close();
}
}catch(IOException e) {
log.error("InputStream or OutputStream close error : {}", e);return false;
}
}return true;
}
}