// 上传文件到URL(基础版,无进度回调) export const uploadFile = async (file: File, uploadUrl: string): Promise => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('PUT', uploadUrl); xhr.setRequestHeader('Content-Type', file.type); xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(); } else { reject(new Error(`Upload failed with status ${xhr.status}`)); } }; xhr.onerror = () => { reject(new Error('Network error during upload')); }; xhr.send(file); }); }; // 支持进度回调和超时的上传实现 export const uploadFileWithProgress = async ( file: File, uploadUrl: string, onProgress?: (progress: number) => void, timeout: number = 30000 ): Promise => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); let timeoutId: number | undefined; xhr.open('PUT', uploadUrl); xhr.setRequestHeader('Content-Type', file.type); // 进度监听 if (onProgress) { xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const progress = Math.round((event.loaded / event.total) * 100); onProgress(progress); } }; } xhr.onload = () => { clearTimeout(timeoutId); if (xhr.status >= 200 && xhr.status < 300) { resolve(); } else { reject(new Error(`Upload failed with status ${xhr.status}`)); } }; xhr.onerror = () => { clearTimeout(timeoutId); reject(new Error('Network error during upload')); }; // 超时处理 timeoutId = setTimeout(() => { xhr.abort(); reject(new Error('上传超时,请检查网络连接')); }, timeout); xhr.send(file); }); };