upload.js 2.9 KB

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