2025-07-17 15:44:34 +08:00

67 lines
2.0 KiB
TypeScript
Raw 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.

// 上传文件到URL基础版无进度回调
export const uploadFile = async (file: File, uploadUrl: string): Promise<void> => {
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<void> => {
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);
});
};