zhengyiming
2025-03-13 9c680ea2c5938d26065232d3a658a9a615e1f827
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
import _ from 'lodash';
import { setOSSLink } from '@life-payment/utils';
import Taro from '@tarojs/taro';
import { FileItem } from '@nutui/nutui-taro/dist/types/__VUE/uploader/type';
 
/**
 * 获取文件扩展名
 */
export function getFileExtension(url: string): string {
  return _.last(url.split('.'));
}
 
export function getFileNameInfo(fileUrl: string) {
  const fileNameList = fileUrl.split('/').pop().split('.');
  const extension = fileNameList.pop();
  const newFileNameList = fileNameList.join('.').split('_');
  if (newFileNameList.length > 1) {
    newFileNameList.pop();
  }
  return {
    fileName: decodeURI(newFileNameList.join('_')),
    extension,
  };
}
 
export function extractFileNameFromUrl(fileUrl: string) {
  const { fileName, extension } = getFileNameInfo(fileUrl);
  return `${fileName}.${extension}`;
}
 
export function urlOmitDomain(url: string) {
  return url.replace(/^https?:\/\/[^/]+/, '');
}
 
const imgReg = /\.(png|jpeg|jpg|webp|gif)$/i;
 
/**
 * 把api返回的路径转换为upload的路径
 */
export function convertApiPath2Url(path: string) {
  return {
    name: extractFileNameFromUrl(path),
    path: urlOmitDomain(path),
    url: setOSSLink(path),
    status: 'success',
    type: imgReg.test(path) ? 'image' : '',
    uid: _.uniqueId(),
  } as FileItem;
}
 
export function convertApi2FormUrlOnlyOne(path: string) {
  return path ? [convertApiPath2Url(path)] : [];
}
 
/**
 * 把upload的路径转换为上传到api的路径
 */
export function convertFormUrl2Api<
  T extends { path?: string; url?: string; status?: FileItem['status'] }
>(urls: T[]) {
  return urls.filter((x) => x.path && x.status === 'success').map((x) => urlOmitDomain(x.path));
}
 
export function convertFilterFormUrl2Api<T extends { path?: string }>(urls: T[]) {
  return urls.filter((x) => x.path);
}
 
export function isFileAllUploaded(fileList: FileItem[]) {
  return fileList.every((x) => !!x.path && x.status === 'success');
}
 
type Base64ListItem = {
  base64: string;
  fileName: string;
};
 
export function base64SaveTolocal(base64List: Base64ListItem[]) {
  const fsm = Taro.getFileSystemManager();
 
  return base64List.map((base64ListItem) => {
    const arrayBuffer = Taro.base64ToArrayBuffer(
      base64ListItem.base64.replace('data:image/png;base64,', '')
    );
    const fileName = `${Taro.env.USER_DATA_PATH}/${base64ListItem.fileName}.png`;
    fsm.writeFileSync(fileName, arrayBuffer, 'binary');
    return fileName;
  });
}