gongxiangp2/lib/pdf-upload-handler.ts

114 lines
3.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* PDF素材上传处理工具
*
* 专门处理品牌VI灵感(PDF)类型的上传逻辑
* 包括:PDF预览图提取、文件处理等
*/
import { promises as fs } from 'fs'
import { generatePdfPreview, isPdfFile } from './pdf-processor'
import { uploadToS3 } from './s3'
/**
* 生成唯一文件名
*/
function generateUniqueFilename(prefix: string, ext: string): string {
const timestamp = Date.now()
const random = require('crypto').randomBytes(8).toString('hex')
return `${prefix}-${timestamp}-${random}${ext}`
}
/**
* PDF上传处理结果
*/
export interface PdfUploadResult {
success: boolean
previewUrl?: string
error?: string
}
/**
* 处理PDF文件上传
* 从PDF文件提取第一页作为预览图
*
* @param pdfFilePath PDF文件路径
* @param existingPreviewUrl 已存在的预览图URL(如果用户手动上传了预览图)
* @returns 处理结果
*/
export async function processPdfUpload(
pdfFilePath: string,
existingPreviewUrl?: string
): Promise<PdfUploadResult> {
try {
// 如果已经有预览图,直接返回
if (existingPreviewUrl && existingPreviewUrl.trim()) {
return {
success: true,
previewUrl: existingPreviewUrl,
}
}
// 检查是否为PDF文件
const isPdf = await isPdfFile(pdfFilePath)
if (!isPdf) {
return {
success: false,
error: '文件不是有效的PDF格式',
}
}
console.log('[PDF Upload] PDF file detected, extracting first page as preview...')
console.log('[PDF Upload] PDF file path:', pdfFilePath)
// 提取PDF第一页作为预览图
const pdfPreviewResult = await generatePdfPreview(pdfFilePath)
console.log('[PDF Upload] PDF预览图提取结果:', {
success: pdfPreviewResult.success,
hasPreviewPath: !!pdfPreviewResult.previewPath,
previewPath: pdfPreviewResult.previewPath,
error: pdfPreviewResult.error,
width: pdfPreviewResult.width,
height: pdfPreviewResult.height
})
if (!pdfPreviewResult.success || !pdfPreviewResult.previewPath) {
const errorMsg = pdfPreviewResult.error || 'PDF预览图提取失败'
console.error('[PDF Upload] ❌ PDF预览图提取失败:', errorMsg)
return {
success: false,
error: errorMsg,
}
}
try {
// 读取预览图并上传到S3
const previewBuffer = await fs.readFile(pdfPreviewResult.previewPath)
const previewFilename = generateUniqueFilename('pdf-preview', '.jpg')
const previewUrl = await uploadToS3(previewBuffer, previewFilename, 'image/jpeg')
console.log('[PDF Upload] PDF preview extracted and uploaded:', previewUrl)
// 清理临时预览图文件
await fs.unlink(pdfPreviewResult.previewPath).catch(() => {})
return {
success: true,
previewUrl,
}
} catch (uploadError) {
console.error('[PDF Upload] Failed to upload PDF preview:', uploadError)
return {
success: false,
error: uploadError instanceof Error ? uploadError.message : '上传预览图失败',
}
}
} catch (error) {
console.error('[PDF Upload] Error processing PDF upload:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'PDF处理失败',
}
}
}