- 원본 대신 400px 썸네일을 렌더해 디코딩/메모리 부담 감소 - 중복 파일은 추가하지 않고 안내 - 이미지 개수 카운터(n/100) 표시 - objectURL 해제 누락 지점 보완
84 lines
2.6 KiB
TypeScript
84 lines
2.6 KiB
TypeScript
import type { ImageUploadResponse, ImageUrlItem } from '../types/api';
|
|
import { compressImageForUpload } from './imageCompression.ts';
|
|
|
|
export const MAX_IMAGES_PER_UPLOAD_TASK = 100;
|
|
|
|
export type ImageUploadRequest = (formData: FormData) => Promise<ImageUploadResponse>;
|
|
export type ImageCompressor = (file: File) => Promise<File>;
|
|
|
|
interface ImageUploadFormOptions {
|
|
imageUrls?: ImageUrlItem[];
|
|
file?: File;
|
|
taskId?: string;
|
|
finalize?: boolean;
|
|
}
|
|
|
|
export function createImageUploadFormData({
|
|
imageUrls = [],
|
|
file,
|
|
taskId,
|
|
finalize,
|
|
}: ImageUploadFormOptions): FormData {
|
|
const formData = new FormData();
|
|
|
|
if (imageUrls.length > 0) {
|
|
formData.append('images_json', JSON.stringify(imageUrls));
|
|
}
|
|
if (taskId) {
|
|
formData.append('task_id', taskId);
|
|
}
|
|
if (finalize !== undefined) {
|
|
formData.append('finalize', String(finalize));
|
|
}
|
|
if (file) {
|
|
formData.append('files', file);
|
|
}
|
|
|
|
return formData;
|
|
}
|
|
|
|
export async function uploadImagesSequentially(
|
|
imageUrls: ImageUrlItem[],
|
|
files: File[],
|
|
sendRequest: ImageUploadRequest,
|
|
compressFile: ImageCompressor = compressImageForUpload
|
|
): Promise<ImageUploadResponse> {
|
|
const totalImageCount = imageUrls.length + files.length;
|
|
if (totalImageCount > MAX_IMAGES_PER_UPLOAD_TASK) {
|
|
throw new Error(`이미지는 최대 ${MAX_IMAGES_PER_UPLOAD_TASK}장까지 업로드할 수 있습니다.`);
|
|
}
|
|
|
|
if (files.length === 0) {
|
|
return sendRequest(createImageUploadFormData({ imageUrls }));
|
|
}
|
|
|
|
let taskId: string | undefined;
|
|
let finalResponse: ImageUploadResponse | undefined;
|
|
|
|
for (let index = 0; index < files.length; index += 1) {
|
|
// Compress and upload one source at a time. This prevents both decoded
|
|
// image buffers and multipart request bodies from accumulating in memory.
|
|
const compressedFile = await compressFile(files[index]);
|
|
const isFirstRequest = index === 0;
|
|
const isLastRequest = index === files.length - 1;
|
|
const formData = createImageUploadFormData({
|
|
imageUrls: isFirstRequest ? imageUrls : [],
|
|
file: compressedFile,
|
|
taskId,
|
|
finalize: isLastRequest,
|
|
});
|
|
|
|
finalResponse = await sendRequest(formData);
|
|
if (!finalResponse.task_id) {
|
|
throw new Error('이미지 업로드 응답에 작업 ID가 없습니다.');
|
|
}
|
|
if (taskId && finalResponse.task_id !== taskId) {
|
|
throw new Error('이미지 업로드 작업 ID가 요청 사이에 변경되었습니다. 다시 시도해주세요.');
|
|
}
|
|
taskId = finalResponse.task_id;
|
|
}
|
|
|
|
// files.length > 0 guarantees that the loop produced a response.
|
|
return finalResponse as ImageUploadResponse;
|
|
}
|