Bootstrap

【小程序上传图片封装2024,支持多图,带进度,上传头像】

import config from './config';

// 支持多图,显示进度
export function uploadImages(count = 1, sourceType, onLoading = null, showProgress = false, fileKey = 'file') {
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count: count, // 可以选择的图片数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
      sourceType, // 可以指定来源是相册还是相机
      success: (chooseResult) => {
        console.log('chooseResult', chooseResult);
        const tempFilePaths = chooseResult.tempFiles;
        const uploadPromises = tempFilePaths.map((filePath, index) => {
          const baseUrl = (env == 'pro' || !env) ? config.BASE_URL : config.DEV_URL;
          const param = 'demo';
          const formData = {
            ...param,
            sign: signStr,
          };
          console.log('filePath:', filePath, 'name:', fileKey, 'formData', formData);
          return new Promise((resolve, reject) => {
            const uploadTask = wx.uploadFile({
              url: `${baseUrl}${config.UPLOAD_URL}`,
              filePath: filePath.tempFilePath,
              name: fileKey,
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                data: JSON.stringify(formData)
              },
              success: (uploadResult) => {
                console.log(uploadResult);
                if (uploadResult.statusCode === 200) {
                  const data = JSON.parse(uploadResult.data);
                  if (returnLocation) {
                    resolve(data);
                    return;
                  }
                  resolve(data.url);
                } else {
                  console.error(`Upload failed with status code ${uploadResult.statusCode}`);
                  reject(new Error(`Upload failed with status code ${uploadResult.statusCode}`));
                }
              },
              fail: (error) => {
                console.error('Upload failed:', error);
                reject(error);
              }
            });

            if (showProgress) {
              uploadTask.onProgressUpdate((res) => {
                console.log(`File ${index + 1} progress: ${res.progress}%`);
                if (onLoading) {
                  onLoading(`上传中... ${res.progress}%`);
                }
              });
            }
          });
        });

        if (onLoading) {
          onLoading('上传中...');
        }

        Promise.all(uploadPromises)
          .then((results) => {
            console.log('上传成功-----', results);
            if (onLoading) {
              onLoading(null); // 传递 null 表示隐藏 loading
            }
            resolve(results);
          })
          .catch((error) => {
            if (onLoading) {
              onLoading(null); // 传递 null 表示隐藏 loading
            }
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
            reject(error);
          });
      },
    });
  });
};

// 上传头像,支持裁剪,小程序自带功能
<button data-type="avatar" open-type="chooseAvatar" bindchooseavatar="handleAvatarChoose">
// 对应js
handleAvatarChoose(e) {
      uploadAvatar(e.detail.avatarUrl).then((url) => {
        console.log('上传成功,返回内容是:', url);
        this.setData({ avatar: url });
      }).catch((error) => {
        console.log(`图片上传失败--${JSON.stringify(error)}`);
      });
 },

// 封装的上传
export function uploadAvatar(avatarUrl) {
  return new Promise((resolve, reject) => {
    const param = {
      nonce: getNum(),
      timestamp: new Date().getTime() + '',
      token: wx.getStorageSync('token') || '',
      userid: wx.getStorageSync('userid') || '',
    };

    const env = wx.getStorageSync('env');
    const baseUrl = (env == 'pro' || !env) ? config.BASE_URL : config.DEV_URL;

    const formData = {
      ...param,
      sign: signStr,
    };
    console.log('filePath:', avatarUrl,  'formData', formData);
    wx.uploadFile({
      url: `${baseUrl}${config.UPLOAD_URL}`,
      filePath: avatarUrl,
      name: 'file', // 后台要绑定的名称
      header: {
        'Content-Type': 'multipart/form-data',
      },
      formData: {
        data: JSON.stringify(formData),
      },
      success: function (res) {
        if (res.statusCode === 200) {
          try {
            const data = JSON.parse(res.data);
            resolve(data.url); // 假设返回的数据中包含图片的 URL
          } catch (error) {
            console.error('JSON parse error:', error);
            reject(new Error('JSON parse error'));
          }
        } else {
          console.error(`Upload failed with status code ${res.statusCode}`);
          reject(new Error(`Upload failed with status code ${res.statusCode}`));
        }
      },
      fail: function (error) {
        console.error('Upload failed:', error);
        reject(error);
      }
    });
  });
};


;