gongxiangp2/components/upload/image-input-handlers.ts

99 lines
2.5 KiB
TypeScript

/**
* 图片输入处理函数
* 包括预览图、展示图、模特图的处理
*/
import { compressPreviewImage, compressAndSliceDisplayImage } from './image-processor'
/**
* 处理预览图选择
*/
export async function handlePreviewImageInput(
files: File[],
onSuccess: (compressedFiles: File[], urls: string[]) => void,
onError: (error: string) => void
) {
if (files.length === 0) return
const imageFiles = files.filter(f => f.type.startsWith('image/'))
if (imageFiles.length === 0) {
onError('请选择图片文件')
return
}
try {
const compressedFiles: File[] = []
const urls: string[] = []
for (const file of imageFiles) {
const compressed = await compressPreviewImage(file)
compressedFiles.push(compressed)
urls.push(URL.createObjectURL(compressed))
}
onSuccess(compressedFiles, urls)
} catch (err) {
console.error('预览图压缩失败:', err)
onError('预览图处理失败,请重试或更换图片')
}
}
/**
* 处理展示图选择(详情页/详情模板:上传原图,后端自动切片)
*/
export async function handleDisplayImageInput(
file: File,
onSuccess: (file: File, url: string) => void,
onError: (error: string) => void
) {
if (!file) return
if (!file.type.startsWith('image/')) {
onError('请选择图片文件')
return
}
try {
// 详情页/详情模板:直接上传原图,不切片(后端会自动切片)
// 只创建预览URL用于前端显示
const url = URL.createObjectURL(file)
onSuccess(file, url)
} catch (err) {
console.error('展示图处理失败:', err)
onError('展示图处理失败,请重试或更换图片')
}
}
/**
* 处理模特图选择
*/
export async function handleModelImagesInput(
files: File[],
onSuccess: (processedFiles: File[], urls: string[]) => void,
onError: (error: string) => void
) {
if (files.length === 0) return
const invalidFiles = files.filter((file) => !file.type.startsWith('image/'))
if (invalidFiles.length > 0) {
onError('请只选择图片文件')
return
}
try {
const processedFiles: File[] = []
const urls: string[] = []
for (const f of files) {
const slices = await compressAndSliceDisplayImage(f)
slices.forEach((sf) => {
processedFiles.push(sf)
urls.push(URL.createObjectURL(sf))
})
}
onSuccess(processedFiles, urls)
} catch (err) {
console.error('模特展示图处理失败:', err)
onError('展示图片处理失败,请重试或更换图片')
}
}