Skip to content

Instantly share code, notes, and snippets.

@xxf1996
Created March 22, 2020 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xxf1996/d69db4da7dadc86c852efb3536b36e63 to your computer and use it in GitHub Desktop.
Save xxf1996/d69db4da7dadc86c852efb3536b36e63 to your computer and use it in GitHub Desktop.
封装qiniu-js的ts文件示例
import * as Qiniu from 'qiniu-js' // 注意qiniu-js并没有export default!
import dayjs from 'dayjs'
import { getQiniuToken } from '@/api/user'
import { QiniuSetting } from '@/api/types'
export interface ObserverNextRes {
/**
* 进度更新回调数据
*/
total: {
/**
* 已上传大小,单位为字节
*/
loaded: number;
/**
* 本次上传的总量控制信息,单位为字节
*/
total: number;
/**
* 当前上传进度,范围:0~100
*/
percent: number;
};
}
export interface ObserverError {
isRequestError: boolean;
code: number;
message: number;
reqId: string;
}
export interface QiniuObserver {
/**
* 接收上传进度信息的回调
*/
next: (res: ObserverNextRes) => void;
/**
* 上传错误回调
*/
error: (err: ObserverError) => void;
/**
* 上传完成后的回调
*/
complete: (info: any) => void;
}
export interface QiniuSubscription {
/**
* 中止当前上传
*/
unsubscribe: () => void;
}
/**
* 七牛云上传资源返回的对象
*/
export interface QiniuObservable {
subscribe: (observer: QiniuObserver) => QiniuSubscription;
}
/**
* 根据文件名取出后缀(带.)
* @param fileName 文件名
*/
function getSuffix (fileName: string): string {
let suffix = '.jpg'
const res = fileName.match(/(\.[!.]+)$/)
if (res) {
suffix = res[1]
}
return suffix
}
/**
* 上传图片文件至七牛云空间
* @param config 七牛云空间配置
* @param img 图片文件
*/
export default async function uploadImage (config: QiniuSetting, img: File): Promise<QiniuObservable | null> {
const res = await getQiniuToken({
AK: config.accessKey,
SK: config.secretKey,
bucket: config.bucket
}) // 获取七牛云空间上传token
if (res.data.token) {
const cur = dayjs().format('YYYYMMDDHHmmss')
const observer: QiniuObservable = Qiniu.upload(
img,
`${config.path}${cur}${getSuffix(img.name)}`, // 文件名
res.data.token
)
return observer
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment