UNPKG

@tinyuploader/sdk

Version:

Large file chunked upload solution SDK, compatible with various UI frameworks.

530 lines (479 loc) 15.9 kB
import { HashCallbackData } from 'hashion'; import { Hashion } from 'hashion'; export declare type BeforeAdd = (file: FileContext) => Promise<boolean | any> | boolean | any; export declare type BeforeRemove = BeforeAdd; /** * 回调函数名称 */ export declare const Callbacks: { /** 文件超出limit限制 */ readonly Exceed: "exceed"; /** 单个文件添加成功 */ readonly FileAdded: "fileAdded"; /** 文件添加失败 */ readonly FileAddFail: "fileAddFail"; /** 所有文件添加成功 */ readonly FilesAdded: "filesAdded"; /** 文件状态改变 */ readonly FileChange: "fileChange"; /** 文件删除 */ readonly FileRemove: "fileRemove"; /** 文件开始计算hash */ readonly FileReadStart: "fileReadStart"; /** 文件计算进度 */ readonly FileReadProgress: "fileReadProgress"; /** 文件hash计算完成 */ readonly FileReadEnd: "fileReadEnd"; readonly FileReadFail: "fileReadFail"; /** 暂停操作 */ readonly FilePause: "filePause"; /** 重新上传操作 */ readonly FileResume: "fileResume"; /** 文件上传进度 */ readonly FileProgress: "fileProgress"; /** 文件上传成功 */ readonly FileUploadSuccess: "fileUploadSuccess"; /** 文件上传失败 */ readonly FileUploadFail: "fileUploadFail"; /** 文件合并成功 */ readonly FileSuccess: "fileSuccess"; /** 文件上传失败合并失败 */ readonly FileFail: "fileFail"; /** 所有文件上传成功 */ readonly AllFileSuccess: "allFileSuccess"; }; /** * 校验上传状态请求 */ declare type CheckRequest = (file: FileContext, data: Record<string, any>, headers: Record<string, string>) => Promise<CheckRequestResult> | CheckRequestResult; declare type CheckRequestResult = { status: CheckStatus; data?: any; }; /** * check 文件状态 */ export declare const CheckStatus: { /** 文件还没上传 */ readonly None: "none"; /** 部分上传成功 */ readonly Part: "part"; /** 准备合并 */ readonly WaitMerge: "waitMerge"; /** 上传成功 */ readonly Success: "success"; }; export declare type CheckStatus = (typeof CheckStatus)[keyof typeof CheckStatus]; export declare class Chunk { /** Uploader实例 */ uploader: Uploader; /** Uploader配置 */ options: UploaderOptions; /** FileContext实例 */ file: FileContext; /** 文件唯一ID */ fileId: string; /** 文件二进制数据 */ rawFile: File; /** 文件hash值 */ fileHash: string; /** 文件名称 */ filename: string; /** 文件大小 */ totalSize: number; /** 分片大小 */ chunkSize: number; /** 分片总数 */ totalChunks: number; /** chunk唯一id */ uid: string; /** chunk在索引值 */ chunkIndex: number; /** chunk状态 */ status: ChunkStatus; /** chunk bit 起始位置 */ startByte: number; /** chunk bit 结束位置 */ endByte: number; /** chunk 大小 */ size: number; /** chunk最大重试次数 */ maxRetries: number; /** chunk 真实上传进度 */ progress: number; /** chunk fake进度 */ fakeProgress: number; /** timer */ timer: any; /** 上传请求 */ request: RequestResult | null; /** 自定义上传请求 */ customRequest: Request_2; constructor(file: FileContext, index: number); onSuccess(e: any, response: any, resolve: Function, reject: Function): void; onFail(e: any, reject: Function): void; onProgress(e: ProgressEvent): void; prepare(): { [x: string]: any; hash: string; id: string; fileId: string; index: number; filename: string; size: number; totalSize: number; totalChunks: number; }; send(): Promise<unknown>; abort(): void; } /** * chunk上传状态 */ export declare const ChunkStatus: { /** chunk初始化状态是Ready */ readonly Ready: "ready"; /** chunk创建请求成功,Promise处于Pending状态 */ readonly Pending: "pending"; /** chunk上传中 */ readonly Uploading: "uploading"; /** chunk上传成功 */ readonly Success: "success"; /** chunk上传失败(所有重试次数完成后 都不成功) */ readonly Fail: "fail"; }; export declare type ChunkStatus = (typeof ChunkStatus)[keyof typeof ChunkStatus]; export declare const create: (options?: UploaderOptions) => Uploader; export declare const defaultOptions: UploaderOptions; declare function each<T>(collection: Eachable<T>, func: EachCallback<T>, context?: any): void; declare type Eachable<T> = T[] | Record<string, T>; declare type EachCallback<T> = (value: T, key: number | string, collection: Eachable<T>) => boolean | void; declare function extend(): any; export declare class FileContext { /** uploader实例 */ uploader: Uploader; /** uploader配置项 */ options: UploaderOptions; /** 计算hash的方法 */ hasher: Hashion; /** 文件ID */ id?: string; /** 文件唯一ID */ uid: string; /** 文件状态 */ status: FileStatus | ''; /** 文件状态变更记录 */ prevStatusLastRecord: string[]; /** 文件二进制 */ rawFile: File; /** 文件名称 */ name: string; /** 文件大小 */ size: number; /** 文件类型 */ type: string; /** 文件hash值 */ hash: string; /** 文件http地址 */ url: string; /** 文件上传进度 */ progress: number; /** 分片大小 */ chunkSize: number; /** 分块chunk集合 */ chunks: Chunk[]; /** 分片总数 */ totalChunks: number; /** 上传中chunk集合 */ uploadingChunks: Set<Chunk>; /** 文件读取进度(hash计算进度) */ readProgress: number; /** 错误信息 */ errorMessage: string; /** 文件自定义data */ data: Record<string, any>; /** abortRead */ abortRead: any; constructor(file: File, uploader: Uploader, defaults: UserFile | null); generateId(): string; setErrorMessage(message: string): this; setData(data: Record<string, any>): this; get renderSize(): string; changeStatus(newStatus: FileStatus): void; isInit(): boolean; isAddFail(): boolean; isReading(): boolean; isReady(): boolean; isCheckFail(): boolean; isUploading(): boolean; isUploadSuccess(): boolean; isUploadFail(): boolean; isSuccess(): boolean; isFail(): boolean; isPause(): boolean; isResume(): boolean; createChunks(): void; read(): Promise<void>; _computeHash(): Promise<Required<HashCallbackData>>; _processData(processType: ProcessType): { [x: string]: any; }; checkRequest(): Promise<void>; addUploadingChunk(chunk: Chunk): void; removeUploadingChunk(chunk: Chunk): void; upload(): Promise<void>; setProgress(): void; uploadFail(): void; uploadSuccess(): void; merge(): Promise<void>; mergeFail(): void; success(): void; _continueUpload(): void; cancel(): void; remove(): Promise<void>; pause(): void; resume(): void; retry(): void; } /** * 文件状态 */ export declare const FileStatus: { /** 文件初始化状态 */ readonly Init: "init"; /** 文件添加失败, 添加文件时允许beforeAdd中失败的文件添加到列表,但是状态为AddFail */ readonly AddFail: "addFail"; /** 文件读取中(计算hash中) */ readonly Reading: "reading"; /** 文件hash计算完成;准备上传 */ readonly Ready: "ready"; /** checkRequest 存在时,切checkRequest失败 */ readonly CheckFail: "checkFail"; /** 文件上传中 */ readonly Uploading: "uploading"; /** 文件上传完成;所有chunk上传完成,准备合并文件 */ readonly UploadSuccess: "uploadSuccess"; /** 文件上传失败;有chunk上传失败 */ readonly UploadFail: "uploadFail"; /** 文件上传成功 且 合并成功 */ readonly Success: "success"; /** 文件合并失败 */ readonly Fail: "fail"; /** 文件暂停上传 */ readonly Pause: "pause"; /** 文件恢复上传 */ readonly Resume: "resume"; /** 文件删除 */ readonly Removed: "removed"; }; export declare type FileStatus = (typeof FileStatus)[keyof typeof FileStatus]; declare const generateUid: (prex?: string) => string; declare const isArray: (thing: any) => boolean; declare const isBlob: (thing: any) => boolean; declare const isBoolean: (thing: any) => boolean; declare const isDefined: (thing: any) => boolean; declare const isFunction: (thing: any) => boolean; declare const isObject: (thing: any) => boolean; declare const isPlainObject: (thing: any) => boolean; declare const isPromise: (promise: any) => any; declare const isString: (thing: any) => boolean; /** * 文件合并自定义接口 */ declare type MergeRequest = (file: FileContext, data: Record<string, any>, headers: Record<string, string>) => Promise<MergeRequestResult> | MergeRequestResult; declare type MergeRequestResult = boolean | string; declare const parseData: <T extends Record<string, any>>(data: T | (() => T)) => T; /** * Uploader插件 */ declare type Plugin_2 = { pluginName: string; }; export { Plugin_2 as Plugin } /** * 文件上传 接口调用类型 */ export declare const ProcessType: { /** check接口 */ readonly Check: "check"; /** upload chunk接口 */ readonly Upload: "upload"; /** merge接口 */ readonly Merge: "merge"; }; export declare type ProcessType = (typeof ProcessType)[keyof typeof ProcessType]; declare const renderSize: (value: number | string | null | undefined) => string; declare function request(options: RequestOptions): RequestResult; declare type Request_2 = typeof request; export { Request_2 as Request } export declare type RequestOptions = { /** http method类型 */ method?: 'POST' | 'GET' | 'PUT'; /** 是否该使用类似 cookie、Authorization 标头 */ withCredentials?: boolean; /** 响应的数据类型 */ responseType?: 'json' | 'blob' | 'arraybuffer' | 'text' | ''; /** 上传接口endpoint */ action: string; /** 自定义上传参数 */ data: Record<string, any>; /** 上传接口headers */ headers: Record<string, string>; /** 文后端接收文件name */ name: string; /** 自定义data 包括file上自定义的data */ query: Record<string, any>; /** 响应成功回调 */ onSuccess?: (e: any, request: any) => void; /** 响应失败回调 */ onFail?: (e: any, request: any) => void; /** 上传进度回调 */ onProgress?: (e: ProgressEvent) => void; }; export declare type RequestResult = { abort: () => void; canceled?: boolean; }; declare const sleep: (time?: number, mockError?: boolean) => Promise<unknown>; declare const slice: (start?: number, end?: number, contentType?: string) => Blob; declare const throttle: <T extends (...args: any[]) => void>(fn: T, wait?: number) => ((...args: Parameters<T>) => void); export declare class Uploader { /** 挂载事件容器实例 */ private container; /** 事件派发监听 */ private event; /** 配置项 */ options: UploaderOptions; /** 计算hash方法实例 */ hasher: Hashion | null; /** 文件列表 */ fileList: Array<FileContext>; constructor(options?: UserUploaderOptions); on(name: string, fn: Function): void; emit(name: string, ...args: any[]): void; emitCallback(name: string, ...args: any[]): void; updateData(data: Record<string, any>): void; updateHeaders(headers: Record<string, string>): void; setOption(options: UserUploaderOptions): void; use(plugin: Plugin_2): void; formatAccept(accept?: string | string[]): string | string[] | undefined; assignBrowse(domNode: HTMLElement, userAttributes?: UserAttributes): void; assignDrop(domNode: HTMLElement): void; _setupFileListeners(): void; setDefaultFileList(fileList: UserFile[]): void; addFiles(arrayLike: File[]): Promise<void>; _handleFileAdd(file: FileContext, beforeAdd: BeforeAdd): Promise<void>; upload(): Promise<void>; submit(): void; remove(file: FileContext): void; clear(): void; doRemove(file: FileContext): void; pause(file: FileContext): void; resume(file: FileContext): void; retry(file: FileContext): void; destroy(): void; } /** * 上传实例参数配置 */ export declare type UploaderOptions = { /** * input 属性相关 */ /** 允许文件上传类型 https://developer.mozilla.org/zh-CN/docs/Web/HTML/Reference/Attributes/accept*/ accept: string; /** 是否允许上传多个文件 https://developer.mozilla.org/zh-CN/docs/Web/HTML/Reference/Attributes/multiple */ multiple: boolean; /** * 文件相关 */ /** 文件列表 */ fileList: UserFile[]; /** 最大上传数 */ limit: number; /** 是否自动上传 */ autoUpload: boolean; /** 自定义uid计算方法 */ customGenerateUid?: (file: FileContext) => string; /** 添加文件之前校验 */ beforeAdd: BeforeAdd; /** 删除文件之前校验 */ beforeRemove: BeforeRemove; /** 添加失败时是否删除文件 */ addFailToRemove: boolean; /** 分片大小 */ chunkSize: number; /** fake进度条 */ fakeProgress: boolean; /** 是都计算文件hash */ withHash: boolean; /** 是否使用 Web Worker */ useWebWoker: boolean; /** * 上传逻辑相关 */ /** 后端接收文件对象名称 */ name: string; /** 上传接口 endPoint */ action: string; /** */ customRequest: null; /** 是否该使用类似 cookie、Authorization 标头 */ withCredentials: boolean; /** 自定义上传参数 */ data: Record<string, any> | (() => Record<string, any>); /** 上传接口headers */ headers: Record<string, string> | (() => Record<string, string>); /** 接口是否成功逻辑 */ requestSucceed: (xhr: any) => boolean; /** 最大并发数量 */ maxConcurrency: 6; /** 最大重试次数 */ maxRetries: 3; /** 重试间隔(单位ms)*/ retryInterval: 1000; /** 校验文件上传状态 */ checkRequest: CheckRequest; /** 文件merge请求 */ mergeRequest: MergeRequest; /** 用户设置自定义data */ processData: <T>(data: T, processType: ProcessType) => T; }; declare type UserAttributes = { /** 允许文件上传类型 */ accept?: string; /** 是否允许上传多个文件 */ multiple?: boolean; }; export declare type UserFile = { id: string | number; name: string; url: string; } & File; /** * 用户配置参数 */ export declare type UserUploaderOptions = Partial<UploaderOptions>; declare namespace Utils { export { sleep, throttle, isDefined, isFunction, isObject, isPlainObject, isBlob, isArray, isPromise, isString, isBoolean, generateUid, each, extend, parseData, slice, renderSize } } export { Utils } export { }