Blame view

common/utils/upload.js 2.07 KB
c293da23   刘淇   新园林init
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
  import globalConfig from '@/common/config/global';
  import cache from '@/common/utils/cache';
  
  export const uploadImages = (files, options = {}) => {
    const opts = { count: 9, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], showLoading: true, ...options };
    const token = cache.get(globalConfig.cache.tokenKey);
  
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      return Promise.reject('未登录');
    }
  
    if (files.length > opts.count) {
      uni.showToast({ title: `最多上传${opts.count}张`, icon: 'none' });
      return Promise.reject('超出数量');
    }
  
    if (opts.showLoading) uni.showLoading({ title: '上传中...' });
  
    const uploadPromises = files.map(filePath => {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: globalConfig.api.uploadUrl,
          filePath,
          name: 'file',
          header: { 'Authorization': `Bearer ${token}` },
          formData: opts.formData || {},
          success: (res) => {
            const data = JSON.parse(res.data);
            if (data.code === 200) resolve(data.data);
            else {
              uni.showToast({ title: data.msg || '上传失败', icon: 'none' });
              reject(data);
            }
          },
          fail: (err) => {
            uni.showToast({ title: '上传失败', icon: 'none' });
            reject(err);
          }
        });
      });
    });
  
    return Promise.all(uploadPromises)
      .then(results => {
        if (opts.showLoading) uni.hideLoading();
        return results;
      })
      .catch(err => {
        if (opts.showLoading) uni.hideLoading();
        return Promise.reject(err);
      });
  };
  
  export const chooseAndUploadImages = (options = {}) => {
    const opts = { count: 9, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], ...options };
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: opts.count,
        sizeType: opts.sizeType,
        sourceType: opts.sourceType,
        success: (res) => {
          uploadImages(res.tempFilePaths, opts).then(resolve).catch(reject);
        },
        fail: reject
      });
    });
  };