upload.js 3.2 KB

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