123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- 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 originalName = file.name || '';
- let filePath = file.path || "";
- let pathName = filePath ? filePath.substr(filePath.indexOf('//tmp/') + 6) : file.url.substr(file.url.lastIndexOf('/') + 1);
-
- //获取文件后缀(包含.)
- let ext = pathName.substr(pathName.lastIndexOf('.'));
- //文件原始名称
- let fileName = originalName.split(ext)[0];
- // 对象键的最大长度为850个字节(按照一个汉字两个字节计算,如果原始文件名超过200个汉字就截断)
- fileName = fileName.length > 200? fileName.substr(0, 200) : fileName;
- //时间戳
- let timestamp = dayjs().valueOf();
- //文件名称:文件原始名称 + 时间戳 + 文件在本地的临时路径
- let name = `${fileName? fileName + '_' : ''}${timestamp}_${pathName}`;
- // 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
|