38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { apiBase } from './api';
|
|
|
|
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
|
|
|
export type UploadFileResult = {
|
|
url: string;
|
|
ossKey: string;
|
|
bucket: string;
|
|
mock: boolean;
|
|
};
|
|
|
|
/** 经 API 服务端转存 OSS */
|
|
export async function uploadFileToOss(
|
|
file: File,
|
|
options: { bizType: string; mediaType?: OssMediaType },
|
|
): Promise<UploadFileResult> {
|
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
formData.append('bizType', options.bizType);
|
|
formData.append('mediaType', mediaType);
|
|
|
|
const headers: Record<string, string> = {
|
|
'X-Client-App': 'USER_H5',
|
|
};
|
|
const token = localStorage.getItem('accessToken');
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
|
|
const res = await fetch(`${apiBase}/common/resources/upload`, {
|
|
method: 'POST',
|
|
headers,
|
|
body: formData,
|
|
});
|
|
const json = await res.json();
|
|
if (json.code !== 0) throw new Error(json.message || '上传失败');
|
|
return json.data as UploadFileResult;
|
|
}
|