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();

}

相关推荐
非凡ghost20 小时前
Xournal++(PDF文档注释工具) 中文绿色版
学习·pdf·生活·软件需求
MonkeyKing_sunyuhua20 小时前
使用ARQ做PDF OCR和 图片OCR的任务的方案
pdf·ocr
2501_9307077821 小时前
如何使用C#代码在 PDF 中添加或删除附件
pdf
m5655bj1 天前
如何使用 Python 调整 PDF 页面顺序?
python·pdf
YuanYWRS1 天前
办公基础:实现PDF中表单不改变格式的情况下转成excel
pdf·excel
E_ICEBLUE2 天前
PDF vs PDF/A:区别、场景与常用转换方法(2025 全面解读)
python·pdf
TextIn智能文档云平台2 天前
从散乱资料到智能知识库:基于TextIn与Coze的RAG实战
人工智能·pdf·知识库·rag·coze·文档解析
m0_564914922 天前
图片怎么快速转为PDF?PDF怎么快速转为图片?
pdf
2501_930707782 天前
如何使用C#代码将多张图片整合为一个PDF文档
开发语言·pdf·c#
拓端研究室2 天前
赢战2025电商新趋势下的增长策略报告:平台格局、跨境趋势、大促消费|附600+份报告PDF、数据、可视化模板汇总下载
大数据·pdf