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

}

相关推荐
ComPDFKit16 分钟前
ComPDF 与 Aspose:转换 SDK 的全面比较
pdf
优选资源分享1 小时前
PDF 电子签章工具 v5.0:全能处理PDF电子签章
pdf
Arvin_Zhang20161 小时前
使用python实现从PDF格式的control mapping获取gross die数量
python·pdf
徐同保1 小时前
上传文件,在前端用 pdf.js 提取 上传的pdf文件中的图片
前端·javascript·pdf
CodeCraft Studio1 小时前
国产化PDF处理控件Spire.PDF教程:使用Python批量自动化将PDF转换为黑白(灰度)
python·pdf·自动化·spire.pdf·文档自动化·pdf开发组件·国产化文档组件
成旭先生1 小时前
文档(如word、ppt、pdf等)在线预览解决方案:基于HTML转换的技术实践与对比
pdf·word·powerpoint
m5655bj2 小时前
使用 C# 将 RTF 文档转换为 PDF 格式
pdf·c#
开开心心_Every20 小时前
免费进销存管理软件:云端本地双部署
java·游戏·微信·eclipse·pdf·excel·语音识别
winfredzhang1 天前
从零构建:手写一个支持“高度定制化排版”的 Chrome 网页摘录插件
chrome·pdf·插件·epub·零碎信息归档
裴嘉靖1 天前
前端获取二进制文件并预览的完整指南
前端·pdf