upload.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import {toast} from "../utils/utils";
  2. import dayjs from "dayjs";
  3. import Api from "./api";
  4. const COS = require('../utils/cos-wx-sdk-v5')
  5. const Bucket = 'college-file-1254259530';
  6. const Region = 'ap-beijing';
  7. class Upload {
  8. static getCos(){
  9. return new COS({
  10. // 必选参数
  11. async getAuthorization(options, callback) {
  12. const res = await Api.getCosInfo();
  13. callback({
  14. TmpSecretId: res.data.credentials.tmpSecretId,
  15. TmpSecretKey: res.data.credentials.tmpSecretKey,
  16. XCosSecurityToken: res.data.credentials.sessionToken,
  17. StartTime: res.data.startTime,
  18. ExpiredTime: res.data.expiredTime,
  19. });
  20. }
  21. });
  22. }
  23. static async uploadRes(uploadPath = '', file) {
  24. let name;
  25. if (file.type == 'image') {
  26. name = dayjs().valueOf() + '.png';
  27. }
  28. if (file.type == 'video') {
  29. name = dayjs().valueOf() + '.mp4';
  30. }
  31. if (file.name) {
  32. name = file.name;
  33. }
  34. const cos = this.getCos();
  35. name = name || file.url.substr(file.url.lastIndexOf('/') + 1);
  36. return new Promise((resolve, reject) => {
  37. cos.postObject({
  38. Bucket: Bucket,
  39. Region: Region,
  40. Key: uploadPath + name,
  41. FilePath: file.url
  42. }, async function (err, data) {
  43. if (!err) {
  44. if (data.headers.location) {
  45. file.url = data.headers.location;
  46. } else {
  47. file.url = `https://${data.Location}`;
  48. }
  49. file.fileExtension = file.url.substr(file.url.lastIndexOf('.') + 1);
  50. resolve()
  51. } else {
  52. reject(err.msg)
  53. toast(err.msg)
  54. }
  55. }
  56. );
  57. });
  58. }
  59. static async deleteRes(uploadPath = '', url) {
  60. return new Promise((resolve, reject) => {
  61. const cos = this.getCos();
  62. const name = url.substr(url.lastIndexOf('/') + 1);
  63. cos.deleteObject({
  64. Bucket: Bucket,
  65. Region: Region,
  66. Key: uploadPath + name,
  67. }, function (err, data) {
  68. if (!err) {
  69. resolve()
  70. } else {
  71. toast(err.msg)
  72. }
  73. });
  74. });
  75. }
  76. }
  77. export default Upload