pdf文件上传下载记录

一:上传单个pdf文件并用hash重命名及判断文件是不是已经上传过,可以参考hash图片

@PostMapping("/uploadPdfFileSingle")

public String uploadPdfFileSingle(@RequestPart("file") MultipartFile file) {

System.err.println("开始文件上传");

if (file.isEmpty()) {

System.err.println("File cannot be empty");

}

if (!"application/pdf".equals(file.getContentType())) {

System.err.println("Only PDF files are allowed");

}

try {

// 生成文件哈希可以参考图片hash'那篇文章

String fileHash = calculateFileHash(file.getInputStream());

// 处理扩展名

String originalFileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));

String fileExtension = originalFileName.contains(".")

? originalFileName.substring(originalFileName.lastIndexOf("."))

: "";

// 使用哈希值作为文件名

String storedFileName = fileHash + fileExtension;

// 创建目录 pdpdf是配置文件配置的根目录

Path uploadPath = Paths.get(pgPdf).toAbsolutePath().normalize();

if (!Files.exists(uploadPath)) {

Files.createDirectories(uploadPath);

}

// 检查文件是否已存在

Path targetLocation = uploadPath.resolve(storedFileName);

if (Files.exists(targetLocation)) {

System.err.println("File is exist"); // 文件已存在

}

// 保存文件

Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

System.err.println(storedFileName);

} catch (IOException ex) {

ex.printStackTrace();

throw new RuntimeException("File storage failed");

}

}

二:对应的下载方法

@GetMapping("/downLoadPdfFileSingle")

public void downLoadPdfFileSingle(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {

//传的文件名就是上传时打印的文件名storedFileName

File f = new File(pgPdf+fileName);

if (!f.exists()) {

response.sendError(404, "File not found!");

return;

}

BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

byte[] buf = new byte[1024];

int len = 0;

response.reset(); // 非常重要

//下载

response.setContentType("application/x-msdownload");

response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());

OutputStream out = response.getOutputStream();

while ((len = br.read(buf)) > 0)

out.write(buf, 0, len);

br.close();

out.close();

}

相关推荐
小贺儿开发16 小时前
Unity3D 心理沙盘互动演示
unity·ai·pdf·人机交互·工具·互动·心理沙盘
私人珍藏库19 小时前
[Windows] PDF工具箱 PDF24 Creator 11.30.0
windows·pdf·工具·软件·多功能
彭于晏Yan19 小时前
基于iText7的动态PDF生成技术方案
spring boot·pdf
悟乙己20 小时前
Advanced RAG 02:揭秘 PDF 解析
ai·pdf·llm·文档解析
lq123321020 小时前
PDF工具箱 PDF24 Creator 11.30.0
pdf
忧郁的Mr.Li2 天前
JAVA工具类---PDF电子签章工具类
java·pdf
AscendKing2 天前
免费、易用、覆盖全平台的网页转 PDF 工具
pdf·html·网页保存·网页保存为pdf·保存网页位pdf
优化控制仿真模型2 天前
【26年6月四级】英语四级高频核心词汇1500个pdf电子版+真题
经验分享·pdf
优化控制仿真模型2 天前
【26大英赛】2012-2026年全国大学生英语竞赛ABCD类历年真题、样题及答案电子版PDF
经验分享·pdf
开开心心_Every2 天前
内存清理软件灵活设置,自动阈值快捷键清
运维·服务器·pdf·web3·电脑·excel·共识算法