UploadHelper.ts 3.57 KB
import type {FileInfo} from "lib/src/core/bean/FileInfo";

type UploadResponseBody = Partial<FileInfo> & {
    message?: unknown;
    response?: unknown;
    status?: unknown;
};

function parseUploadResponse(data: unknown): UploadResponseBody {
    try {
        const parsed = typeof data === 'string' ? JSON.parse(data) : data;
        if (parsed && typeof parsed === 'object') {
            return parsed as UploadResponseBody;
        }
        throw new Error('服务器响应异常');
    } catch (error) {
        if (error instanceof Error && error.message === '服务器响应异常') {
            throw error;
        }
        throw new Error('服务器响应异常');
    }
}

function resolveTempFilePath(tempFile: any): string {
    const candidates = [
        tempFile?.path,
        tempFile?.tempFilePath,
        tempFile?.file?.path,
        tempFile?.file?.tempFilePath,
    ];
    const filePath = candidates.find((candidate) =>
        typeof candidate === 'string' && candidate.trim().length > 0
    );
    return typeof filePath === 'string' ? filePath : '';
}

function resolveUploadErrorMessage(body: UploadResponseBody | null, statusCode: number): string {
    const response = body?.response;
    if (typeof response === 'string' && response.trim()) {
        return response;
    }
    const message = body?.message;
    if (typeof message === 'string' && message.trim()) {
        return message;
    }
    return `上传失败(${statusCode})`;
}

export function getUploadErrorMessage(error: unknown, fallback = '图片上传失败'): string {
    if (typeof error === 'string' && error.trim()) {
        return error;
    }
    if (error instanceof Error && error.message.trim()) {
        return error.message;
    }
    return fallback;
}

/**
 * 文件上传
 * @param tempFile
 * @param url
 * @param token
 */
export function uploadFiles(tempFile: any, url: string, token: string): Promise<FileInfo> {
    const filePath = resolveTempFilePath(tempFile);
    if (!filePath) {
        return Promise.reject(new Error('图片路径无效'));
    }
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: url,
            filePath,
            name: 'file',
            file: tempFile?.file ?? tempFile,
            header: {'Authorization': 'Bearer ' + token},
            success: res => {
                let body: UploadResponseBody;
                try {
                    body = parseUploadResponse(res.data);
                } catch (error) {
                    if (res.statusCode < 200 || res.statusCode >= 300) {
                        reject(new Error(`上传失败(${res.statusCode})`));
                    } else {
                        reject(error instanceof Error ? error : new Error(getUploadErrorMessage(error)));
                    }
                    return;
                }
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    reject(new Error(resolveUploadErrorMessage(body, res.statusCode)));
                    return;
                }
                if (body.status === 'error') {
                    reject(new Error(resolveUploadErrorMessage(body, res.statusCode)));
                    return;
                }
                if (typeof body.filePath !== 'string' || !body.filePath.trim()) {
                    reject(new Error('上传成功但未返回文件路径'));
                    return;
                }
                resolve(body as FileInfo);
            },
            fail: () => {
                reject(new Error('网络异常,图片上传失败'));
            }
        });
    });
}