| | |
| | | public class ImageUploadService { |
| | | |
| | | private static final long MAX_IMAGE_SIZE = 10L * 1024 * 1024; |
| | | private static final long MAX_PDF_SIZE = 20L * 1024 * 1024; |
| | | |
| | | private final Path uploadDirectory; |
| | | |
| | |
| | | return new ImageUploadResult("/uploads/" + filename); |
| | | } |
| | | |
| | | public ImageUploadResult uploadPdf(MultipartFile file) { |
| | | if (file == null || file.isEmpty()) { |
| | | throw new BusinessException(ErrorCode.BAD_REQUEST, "请选择 PDF 文件"); |
| | | } |
| | | if (file.getSize() > MAX_PDF_SIZE) { |
| | | throw new BusinessException(ErrorCode.BAD_REQUEST, "PDF 文件大小不能超过 20 MB"); |
| | | } |
| | | try (InputStream input = file.getInputStream()) { |
| | | byte[] header = input.readNBytes(5); |
| | | if (header.length < 5 || header[0] != '%' || header[1] != 'P' || header[2] != 'D' || header[3] != 'F' || header[4] != '-') { |
| | | throw new BusinessException(ErrorCode.BAD_REQUEST, "仅支持 PDF 文件"); |
| | | } |
| | | } catch (IOException exception) { |
| | | throw new BusinessException(ErrorCode.BAD_REQUEST, "无法读取 PDF 文件"); |
| | | } |
| | | String contentType = file.getContentType() == null ? "" : file.getContentType().toLowerCase(Locale.ROOT); |
| | | if (!contentType.isBlank() && !"application/pdf".equals(contentType) && !"application/octet-stream".equals(contentType)) { |
| | | throw new BusinessException(ErrorCode.BAD_REQUEST, "仅支持 PDF 文件"); |
| | | } |
| | | String filename = UUID.randomUUID() + ".pdf"; |
| | | try { |
| | | Files.createDirectories(uploadDirectory); |
| | | Path destination = uploadDirectory.resolve(filename).normalize(); |
| | | if (!destination.startsWith(uploadDirectory)) throw new BusinessException(ErrorCode.BAD_REQUEST, "Invalid PDF filename"); |
| | | Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING); |
| | | } catch (IOException exception) { |
| | | throw new BusinessException(ErrorCode.INTERNAL_ERROR, "保存 PDF 文件失败"); |
| | | } |
| | | return new ImageUploadResult("/uploads/" + filename); |
| | | } |
| | | |
| | | private String detectImageExtension(MultipartFile file) { |
| | | byte[] header = new byte[12]; |
| | | try (InputStream input = file.getInputStream()) { |