Java 检查文件是否是pdf

public static boolean checkPdfType(InputStream inputStream) {
		try {
			byte[] bytes = new byte[200];
			inputStream.read(bytes);
			String string = new String(bytes);
			String substring = string.substring(0, 10);
			if (!substring.contains("PDF")) {
				return false;
			}
		} catch (Exception e) {
			log.error("checkPdfType error", e);
		}
		return true;
	}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!以下是一个用于上传PDF文件Java文件上传接口的实现示例: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @RestController public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "Please select a file to upload."; } try { // 获取文件输入 InputStream inputStream = file.getInputStream(); // 指定上传的目录路径 String uploadDir = "/path/to/upload/dir/"; // 检查文件类型 String originalFilename = file.getOriginalFilename(); if (!originalFilename.toLowerCase().endsWith(".pdf")) { return "Only PDF files are allowed."; } // 创建目标文件的完整路径 String filePath = uploadDir + originalFilename; // 创建目标文件 File targetFile = new File(filePath); // 创建文件输出 FileOutputStream outputStream = new FileOutputStream(targetFile); // 将输入中的数据写入到输出中 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 关闭 inputStream.close(); outputStream.close(); return "File uploaded successfully!"; } catch (IOException e) { e.printStackTrace(); return "Failed to upload file."; } } } ``` 与之前的示例相比,此代码段添加了一个检查文件类型的步骤,确保只允许上传PDF文件。在该示例中,我们假设只接受以`.pdf`为后缀的文件。 请注意,您需要根据实际情况修改上传目录的路径以及处理异常的方式。 希望以上代码能满足您的需求!如果您有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值