工单小程序2024-11-20
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB

3 months ago
  1. // 此方法适用于web
  2. // import OSS from "ali-oss"
  3. import config from '@/config.js'
  4. /**
  5. * 生成一个随机的Key
  6. */
  7. function storeKey() {
  8. let s = [];
  9. let hexDigits = "0123456789abcdef";
  10. for (let i = 0; i < 36; i++) {
  11. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  12. }
  13. s[14] = "4";
  14. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  15. s[8] = s[13] = s[18] = s[23] = "-";
  16. return s.join("");
  17. }
  18. /**
  19. * 根据当天日期在OSS端生成文件夹
  20. */
  21. function storeFolder() {
  22. const date = new Date();
  23. const formatNumber = n => {
  24. n = n.toString()
  25. return n[1] ? n : '0' + n
  26. }
  27. return [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(formatNumber).join('-')
  28. }
  29. export function uploadFileToOSS(file) {
  30. uni.showLoading({
  31. title: '上传中...'
  32. });
  33. return new Promise((resolve,reject) => {
  34. // 创建OSS实例
  35. const client = new OSS(config.aliOss.config);
  36. // 设置文件名和文件目录
  37. const suffix = '.' + file.name.split('.').pop();
  38. let key = storeFolder()
  39. if(key[key.length - 1] != '/') key += '/'
  40. const fileName = key + storeKey() + suffix; // 注意:文件名需要是唯一的
  41. // 使用put接口上传文件
  42. client.multipartUpload(fileName, file, {
  43. headers: {
  44. 'Content-Disposition': 'inline',
  45. 'Content-Type': file.type
  46. }
  47. }).then(res => {
  48. uni.hideLoading();
  49. resolve(config.aliOss.url + res.name);
  50. }).catch(err => {
  51. uni.hideLoading();
  52. reject(err)
  53. })
  54. })
  55. }