upload.js 2.07 KB
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
    });
  });
};