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

}

相关推荐
弓.长.17 分钟前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-pdf — PDF文档查看器
react native·pdf·harmonyos
开开心心就好2 小时前
绿色版PDF多功能工具,支持编辑转换
人工智能·windows·pdf·ocr·excel·语音识别·harmonyos
月巴月巴白勺合鸟月半7 小时前
一次PDF文件的处理(二)
pdf·c#
开开心心就好7 小时前
免费无广告的礼金记账本,安卓应用
java·前端·ubuntu·edge·pdf·负载均衡·语音识别
优化控制仿真模型8 小时前
2015-2025年12月英语六级历年真题及答案PDF电子版(含听力音频)
经验分享·pdf
爱编程的小吴8 小时前
LangChain基础入门:DocumentLoader加载PDF/Markdown文档实战
python·langchain·pdf
软件工程小施同学9 小时前
区块链论文速读 CCF A--CCS 2025 (1) 附pdf下载
pdf·区块链
葡萄城技术团队1 天前
SpreadJS 中“打印”和“导出 PDF”到底该选哪个?
pdf
优化控制仿真模型1 天前
2025年12月英语六级真题及答案解析完整版(第一、二、三套全PDF)
经验分享·pdf
芒果大胖砸1 天前
uniapp 在h5中预览pdf hybrid方法
pdf·uni-app