1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import {toast} from "../utils/utils";
- import dayjs from "dayjs";
- import Api from "./api";
- const COS = require('../utils/cos-wx-sdk-v5')
- const Bucket = 'college-file-1254259530';
- const Region = 'ap-beijing';
- class Upload {
- static async uploadRes(uploadPath = '', file) {
- let name;
- if (file.type == 'image') {
- name = dayjs().valueOf() + '.png';
- }
- if (file.type == 'video') {
- name = dayjs().valueOf() + '.mp4';
- }
- if (file.name) {
- name = file.name;
- }
- name = name || file.url.substr(file.url.lastIndexOf('/') + 1);
- return new Promise((resolve, reject) => {
- const cos = new COS({
- // 必选参数
- async getAuthorization(options, callback) {
- const res = await Api.getCosInfo();
- callback({
- TmpSecretId: res.data.credentials.tmpSecretId,
- TmpSecretKey: res.data.credentials.tmpSecretKey,
- XCosSecurityToken: res.data.credentials.sessionToken,
- StartTime: res.data.startTime,
- ExpiredTime: res.data.expiredTime,
- });
- }
- });
- cos.postObject({
- Bucket: Bucket,
- Region: Region,
- Key: uploadPath + name,
- FilePath: file.url
- }, async function (err, data) {
- if (!err) {
- if (data.headers.location) {
- file.url = data.headers.location;
- } else {
- file.url = `https://${data.Location}`;
- }
- file.fileExtension = file.url.substr(file.url.lastIndexOf('.') + 1);
- resolve()
- } else {
- reject(err.msg)
- toast(err.msg)
- }
- }
- );
- });
- }
- static async deleteRes(uploadPath = '', url) {
- return new Promise((resolve, reject) => {
- const cos = new COS({
- // 必选参数
- async getAuthorization(options, callback) {
- const res = await Api.getCosInfo();
- callback({
- TmpSecretId: res.data.credentials.tmpSecretId,
- TmpSecretKey: res.data.credentials.tmpSecretKey,
- XCosSecurityToken: res.data.credentials.sessionToken,
- StartTime: res.data.startTime,
- ExpiredTime: res.data.expiredTime,
- });
- }
- });
- const name = url.substr(url.lastIndexOf('/') + 1);
- cos.deleteObject({
- Bucket: Bucket,
- Region: Region,
- Key: uploadPath + name,
- }, function (err, data) {
- if (!err) {
- resolve()
- } else {
- toast(err.msg)
- }
- });
- });
- }
- }
- export default Upload
|