接口代码
import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.*; @RestController @RequestMapping(value = "/file") @Slf4j public class FileController { /** * 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"; } /** * 通过上传的文件名,缓冲到本地,后面才能解压、验证 * @param filePath 临时缓冲到本地的目录 * @param file */ public boolean createLocalFile(String filePath,MultipartFile file) { File localFile = new File(filePath); //先创建目录 localFile.mkdirs(); String originalFilename = file.getOriginalFilename(); String path = filePath+"/"+originalFilename; log.info("createLocalFile path = {}", path); localFile = new File(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 = new FileOutputStream(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; } }
过程是:
首先接口接收文件;
创建将要缓冲文件的目录,存在指定目录就不创建;
判断该目录是否有重复的文件名,如果有,先删除再生成,如果没有,就生成文件;
然后将通过文件流以每次1024bytes写入指定目录的文件;
最后关闭流。
更多Java文件操作可使用强大的Java文件工具:org.apache.commons.io.FileUtils;