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

}

相关推荐
傻啦嘿哟1 天前
Python将Excel工作表转换为PDF:从入门到实战
python·pdf·excel
造价女工1 天前
PDF图纸合并:高效整合分散文件,项目归档更轻松
pdf
裤裤兔2 天前
python爬取pdf文件并保存至本地
chrome·爬虫·python·pdf·网络爬虫
曹牧2 天前
Java中处理URL转义并下载PDF文件
java·开发语言·pdf
xuehuayu.cn2 天前
预览img图片文件pdf文件如何鉴权配置请求头token
pdf
造价女工2 天前
PDF图纸拆分:一键解构大文件,精准管理单张图
pdf
好记忆不如烂笔头abc2 天前
标书加密阶段提示合并PDF失败:错误码3
pdf
SJjiemo2 天前
金山PDF定制版
pdf
网络真危险!!2 天前
前端实现 PDF 与 DOCX 预览全方案:从基础到进阶实践
前端·pdf
winfredzhang2 天前
用 Python + wxPython 打造一个万能网页图片一键下载神器(附完整源码 + 详细解析)
python·微信·pdf·遍历·图片·网页·保存