接口代码
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;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架