12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- 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-1302740389';
- const Region = 'ap-beijing';
- class Upload {
- static getCos() {
- return 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,
- });
- }
- });
- }
- 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;
- }
- const cos = this.getCos();
- name = name || file.url.substr(file.url.lastIndexOf('/') + 1);
- return new Promise((resolve, reject) => {
- 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}`;
- // }
- if(!data.Location) {
- let uploadErr = '上传失败!';
- toast(uploadErr);
- reject(uploadErr);
- return;
- }
- // console.log(data.Location);
- file.url = `https://${data.Location}`;
- file.fileExtension = file.url.substr(file.url.lastIndexOf('.') + 1);
- resolve()
- } else {
- toast(err.error.Message)
- reject(err.error.Message)
- }
- });
- });
- }
- static async deleteRes(uploadPath = '', url) {
- return new Promise((resolve, reject) => {
- const cos = this.getCos();
- 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
|