zhengyiming
2025-02-19 df7c6af1c1cfd2e9bda249e381aecb5482120d14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import cryptoJs from 'crypto-js';
import { Base64 } from 'js-base64';
import { OssResource } from '@12333/constants';
import { OSSBaseURL } from '@12333/constants';
import { getFileExtension } from './file';
import { setOSSLink } from './link';
import { Message } from './message';
import { OssSTS } from './ossSTS';
 
function getFormData(options: API.OssSTSReponse) {
  const date = new Date();
  date.setHours(date.getHours() + 1);
  const policyText = {
    expiration: date.toISOString(),
    conditions: [['content-length-range', 0, 1024 * 1024 * 1024]],
  };
  const policy = Base64.encode(JSON.stringify(policyText));
  const signature = cryptoJs.enc.Base64.stringify(
    cryptoJs.HmacSHA1(policy, options.ossAccessSecret)
  );
  const formData = {
    OSSAccessKeyId: options.ossAccessKeyId,
    signature,
    policy,
    success_action_status: '200',
    'x-oss-security-token': options.securityToken,
  };
  return formData;
}
 
// export OssUploadSuccessResult = {
 
// }
 
export type OssUploadOptions = {
  filePath?: string;
  fileDirectory?: string;
  fileType?: string;
  name?: string;
  fail?: (res: TaroGeneral.CallbackResult) => void;
  /** 接口调用成功的回调函数 */
  success?: (
    result: Taro.uploadFile.SuccessCallbackResult,
    ossRes: { path: string; url: string; name: string }
  ) => void;
  xhrState?: string | number;
  customFileName?: (path: string) => string;
  showLoading?: boolean;
};
 
export async function ossUpload(options: OssUploadOptions) {
  function handleFail(e: any) {
    console.log('options: ', options);
    Message.error('上传出错,请尝试重新上传');
    options.fail?.(e);
  }
 
  try {
    const {
      xhrState = 200,
      fileDirectory = OssResource,
      customFileName,
      name = 'file',
      showLoading = true,
    } = options;
 
    const msTime = dayjs(new Date()).format('YYYYMMDDHHmmssSSS');
    const dayInfo = dayjs(new Date()).format('YYYYMMDD');
    const extensionName = getFileExtension(options.filePath);
    const realFileName = name.replace(/\.\w+$/, '');
    const ossFileName = customFileName ? customFileName(options.filePath) : realFileName;
    const fileName = `${fileDirectory}${dayInfo}/${ossFileName}_${msTime}.${extensionName}`;
 
    if (showLoading) {
      Taro.showLoading({
        title: '上传中',
        mask: true,
      });
    }
 
    let res = await OssSTS.getOssSTS();
 
    return Taro.uploadFile({
      url: OSSBaseURL,
      filePath: options.filePath,
      formData: {
        key: fileName,
        ...getFormData(res),
      },
      name: name,
      success(res) {
        if (res.statusCode === xhrState) {
          options.success?.(res, {
            path: fileName,
            url: setOSSLink(fileName),
            name: ossFileName,
          });
        } else {
          handleFail(res);
        }
      },
      fail(e) {
        handleFail(e);
      },
      complete() {
        Taro.hideLoading();
      },
    });
  } catch (error) {}
}