当前位置: 首页 > news >正文

springboot将文件插入到指定路径文件夹,判断文件是否存在以及根据名称删除

解决方案:

直接使用File和数据流实现
1.插入这个是我自己的业务我是将文件转成pdf之后存入指定路径了这个路径是直接定义在了yml里然后在需要的地方注入调用,然后通过file创建空白pdf放到数据流通过:aspose的方法保存

file:upload:dir: D:/data/uploads       # 通用文件上传目录pdfDir: D:/data/uploadPDF  # PDF文件专用目录dowFile: C:\Users\Lenovo\Desktop #下载路径
@Value("${file.upload.pdfDir}")
private String uploadDirPDF;
String fullSourcePath = uploadDir + File.separator + fileName;
String fullPdfPath = uploadDirPDF + File.separator + pdfFileName;
public static void docToPdf(String sourcerFile,String targetFile) {if (!getLicense()) {// 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File(targetFile);  //新建一个空白pdf文档BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));Document doc = new Document(sourcerFile);                    //sourcerFile是将要被转化的word文档doc.save(out, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换out.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时} catch (Exception e) {e.printStackTrace();}
}2.判断文件是否存在
获取路径传入file即可然后调用exists返回来的内容就可以实现
File pdfDir = new File(uploadDirPDF);
if (!pdfDir.exists() && !pdfDir.mkdirs()) {fileData.setRemark("无法创建PDF目录: " + uploadDirPDF);return fileData;
}3.根据名称删除文件
先将数据库的内容删除,数据库删除没有错误成功后删除文档,将名称和路径传入到方法里调用file.delete即可
@RequestMapping("/delMenusTree")
public R delMenusTree(@RequestBody MenuDeleteDTO menuDeleteDTO){String msg= biddingtoolsoftwareService.delMenusTree(menuDeleteDTO.getId());if (msg.equals("删除成功")){String mlname = menuDeleteDTO.getMlname();deleteFileIfExists(uploadDir, mlname);deleteFileIfExists(uploadDirPDF, mlname);}return R.ok(msg);
}
private void deleteFileIfExists(String directory, String fileName) {if (fileName == null || fileName.isEmpty()) {return; // 避免空文件名导致异常}File file = new File(directory, fileName);if (file.exists() && file.isFile()) {if (file.delete()) {log.info("成功删除文件: {}", file.getAbsolutePath());} else {log.error("删除文件失败: {}", file.getAbsolutePath());// 可以选择记录日志或返回更详细的错误信息}}
}

相关文章:

  • 思辨场域丨AR技术如何重塑未来学术会议体验?
  • 绝不强迫登录!Apipost 离线模式正式上线
  • [学习] 在C语言中使用字典(附示例)
  • tkinter Entry(输入框)组件学习指南
  • Ajax-入门
  • React Native【详解】动画
  • 小白的进阶之路系列之十七----人工智能从初步到精通pytorch综合运用的讲解第十部分
  • 【unitrix】 3.4 类型级逻辑运算(bit.rs)
  • 【Docker】docker-compose中的nginx为何突然访问不到服务了?
  • 【CS创世SD NAND征文】STM32户外无线终端管理设备的数据存储方案
  • 拼多多消息对接、支付服务策略(策略+工厂)
  • supervisor /usr/bin/dotnet: cannot execute binary file
  • cili3d笔记20 正交投影3d重建笔记1
  • GoFrame的Gtoken--基于电商项目以及GPT-o3的辅助解惑
  • 如何轻松地将联系人从 iPhone 转移到 iPhone?
  • window显示驱动开发—输出合并器阶段
  • django FileSystemStorage is located outside of the base path component
  • 【前端隐蔽 Bug 深度剖析:SVG 组件复用中的 ID 冲突陷阱】
  • QT的一些介绍
  • Pinia在多步骤表单中的实践应用
  • 网站设计要先做图么/百度经验怎么赚钱
  • 头条今日头条新闻网页版/潍坊seo计费
  • 网址导航网站建站/销售网站
  • 网站建设发票的税点/网络推广免费平台
  • 学校网站建设要求/近期重大新闻事件
  • 大连在哪儿地图/搜索引擎优化英文简称为