expo-popcore-old/lib/api/upload.ts

78 lines
2.2 KiB
TypeScript

import { postApiFileUploadS3 } from '@repo/loomart-sdk';
import { loomartClient } from './loomart-client';
export interface UploadResponse {
success: boolean;
data?: {
url: string;
filename: string;
size: number;
mimeType: string;
};
message?: string;
}
export async function uploadFile(uri: string, type: 'image' | 'video'): Promise<UploadResponse> {
try {
if (uri.startsWith('https://') || uri.startsWith('http://')) {
return {
success: true,
data: {
url: uri,
filename: uri.split('/').pop() || 'file',
size: 0,
mimeType: type === 'image' ? 'image/jpeg' : 'video/mp4',
},
};
}
const response = await fetch(uri);
const blob = await response.blob();
let mimeType = blob.type || (type === 'image' ? 'image/jpeg' : 'video/mp4');
const extensions: Record<string, string> = {
'image/jpeg': 'jpg', 'image/png': 'png', 'image/gif': 'gif', 'image/webp': 'webp',
'video/mp4': 'mp4', 'video/webm': 'webm', 'video/avi': 'avi', 'video/quicktime': 'mov',
};
const extension = extensions[mimeType] || (type === 'image' ? 'jpg' : 'mp4');
const filename = `${type}_${Date.now()}.${extension}`;
const file = new File([blob], filename, { type: mimeType });
const result = await postApiFileUploadS3({
client: loomartClient,
body: { file },
});
const data = result.data as any;
if (data?.status === true && data?.data) {
return {
success: true,
data: {
url: data.data,
filename,
size: file.size,
mimeType,
},
};
}
throw new Error(data?.error?.message || data?.msg || 'Upload failed');
} catch (error) {
console.error('Failed to upload file:', error);
return {
success: false,
message: error instanceof Error ? error.message : '上传失败,请稍后重试',
};
}
}
/**
* 批量上传文件
*/
export async function uploadFiles(
files: Array<{ uri: string; type: 'image' | 'video' }>
): Promise<UploadResponse[]> {
const uploadPromises = files.map(file => uploadFile(file.uri, file.type));
return Promise.all(uploadPromises);
}