Commit ddf56fd2 by 杨铁龙

提取文件上传service

parent 9b9fd218
Showing with 63 additions and 0 deletions
export * from "./upload"
\ No newline at end of file
...@@ -7,3 +7,63 @@ export async function uploadFile(file: File, uploading?: (p: number) => void) { ...@@ -7,3 +7,63 @@ export async function uploadFile(file: File, uploading?: (p: number) => void) {
}); });
return `${sdk.global.baseUrl}${url}`; return `${sdk.global.baseUrl}${url}`;
} }
export const enum UploadType {
Default,
Image,
Camera
}
/**
* x
* @param type UploadType 默认值 UploadType.Default
* @param size 可不传 单位M
* @returns
*/
export function chooseFileAndUpload(type = UploadType.Default, size?: number) {
return chooseFile(type).then(r => {
const sdk = Chat.getSdk();
return sdk.uploadFileV2(r)
})
}
/**
*
* @param type UploadType
* @param size 可不传 单位M
* @returns
*/
export function chooseFile(type = UploadType.Default, size?: number) {
return new Promise<File>((resolve, reject) => {
const target = document.createElement('input');
target.setAttribute('type', 'file');
// 添加这个属性,就可以唤起相机的功能
(type === UploadType.Camera) && target.setAttribute('capture', 'camera');
// 这里如果不加属性 accept 是 "image/*" 或者 "video/*",就默认打开摄像头,既可以拍照也可以录像
(type === UploadType.Image) && target.setAttribute('accept', 'image/*');
target.setAttribute('style', 'display:none');
// 监听改变事件
target.addEventListener('change', (e: Event) => {
// 拿到文件对象
if (e && e.target) {
const t = e.target as HTMLInputElement;
const { files } = t;
if (files) {
// 返回的是一个文件对象
if (size && files[0].size >= size * 1024 * 1024) {
reject(`上传的${type === UploadType.Default ? "文件" : "图片"}太大了~`);
return;
}
resolve(files[0]);
setTimeout(() => target.remove(), 200);
return;
}
}
reject(new Error('系统不支持'));
setTimeout(() => target.remove(), 200);
});
document.body.appendChild(target);
// 这里是模拟点击了input控件
target.click();
});
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment