AliOssUploadCo.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type { AntUploadRequestOption, UploadCoInterface } from "@/components/dynamicf/UploadImageFormItem";
  2. import { RandomUtils, StringUtils } from "@imengyu/imengyu-utils";
  3. import OSS from 'ali-oss';
  4. const client = new OSS({
  5. region: 'oss-cn-shenzhen',
  6. accessKeyId: 'LTAI5t5e7wAQ1FvUA4LCsNs5',
  7. accessKeySecret: 'lhF0SimpatPMHNjmjtIKsWsYwTmJhx',
  8. bucket: 'minnanwenhua',
  9. });
  10. export function useAliOssUploadCo(subPath: string) : UploadCoInterface {
  11. return {
  12. uploadRequest: async (requestOption: AntUploadRequestOption) => {
  13. const uploadPath = `${subPath}/${requestOption.file.name.split('.')[0]}-${RandomUtils.genNonDuplicateID(26)}.${StringUtils.path.getFileExt(requestOption.file.name)}`;
  14. //小于8mb则直接上传,否则分片上传
  15. if (requestOption.file.size < 8 * 1024 * 1024) {
  16. client.put(uploadPath, requestOption.file).then((res) => {
  17. requestOption.onSuccess?.({
  18. url: res.url,
  19. key: uploadPath,
  20. }, null);
  21. }).catch((err) => {
  22. requestOption.onError?.(err, {});
  23. })
  24. } else {
  25. client.multipartUpload(uploadPath, requestOption.file, {
  26. progress(percentage) {
  27. requestOption.onProgress({ percent: percentage * 100 })
  28. },
  29. }).then((res) => {
  30. requestOption.onSuccess?.({
  31. url: client.generateObjectUrl(uploadPath),
  32. key: uploadPath,
  33. }, null);
  34. }).catch((err) => {
  35. requestOption.onError?.(err, {});
  36. });
  37. }
  38. },
  39. getUrlByUploadResponse: (response: unknown) => {
  40. return (response as any).url as string;
  41. },
  42. }
  43. }