import { getFilemd5sum, getBase64 } from './utils.js' interface upload_sdk { //初始化文件 md5 generateMd5: (file: File) => any //初始化图片 base64 generateBase64: (file: File) =>any //上传 action: () => Promise //成功返回函数 onSuccess: () => string //续传 onContinue: () => number //错误 onError: () => number //http 请求 post: () => Promise } class UploadSdk implements upload_sdk { private host: string private origin: string private token: string private file: File private base64: any private BYTES_PER_CHUNK: number = 1024 * 1024 private IMAGE_MULTIPART = '/multipart/upload/' private VIDEO_MULTIPART = '/upload/' private chunkNum: any private chunkSize: any private fileType: any private fileSize: any private base64Body: any private md5: any private offset = 0; //用于断点续传,默认为 0 constructor(host: string, origin: string, token: string, file: File){ this.host = host this.origin = origin this.token = token this.file = file this.fileSize = file.size this.fileType = file.type this.chunkNum = this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK):1 this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize:this.BYTES_PER_CHUNK } generateMd5 = async () => { let md5 = await getFilemd5sum(this.file) return md5 } generateBase64 = async () => { let base64 = await getBase64(this.file) return base64 } //上传 action = () => { this.md5 = this.generateMd5() this.base64Body = this.generateBase64() return this.post() } //成功返回函数 onSuccess = () => { return 'success' } //续传 onContinue = () => { return 90 } //错误 onError = () => { return 200 } post = () => { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest() xhr.open("POSt", 'http://api.links123.net/mps/v1/'+this.IMAGE_MULTIPART+'forum', true) xhr.withCredentials = true; xhr.setRequestHeader('Authorization', `Bearer ${this.token}`); xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); xhr.setRequestHeader('Accept', 'application/json'); xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',this.fileSize) xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1+'') xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',this.chunkNum) xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',this.chunkSize) xhr.setRequestHeader('LINK_UPLOAD_OFFSET',this.offset+'') xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',this.md5) xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE','jepg') xhr.send(JSON.stringify({body: this.base64Body})) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) { resolve(xhr.responseText) } else { reject(xhr.status) } } } }) } }