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

javascript 复制代码
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);
      }
    });
  });
};
相关推荐
计算机徐师兄4 小时前
Java基于SSM框架的互助学习平台小程序【附源码、文档】
小程序·互助学习·互助学习平台小程序·java互助学习微信小程序·互助学习微信小程序·互助学习平台微信小程序
西农小陈6 小时前
Python-基于PyQt5,wordcloud,pillow,numpy,os,sys的智能词云生成器
开发语言·python·小程序·pycharm·numpy·pyqt·pillow
说私域8 小时前
开源AI智能名片2+1链动模式S2B2C商城小程序:重塑私域流量运营格局
人工智能·小程序·流量运营
Colinnian11 小时前
微信小程序中在一个大边框里给每个小边框均匀分配空间
微信小程序·小程序·notepad++
说私域1 天前
今日头条公域流量引流新径:开源 AI 智能名片 2 + 1 链动模式 S2B2C 商城小程序融合之道
人工智能·小程序
曾经的三心草1 天前
小程序-基础加强
小程序·基础加强
说私域1 天前
智能调度体系与自动驾驶技术优化运输配送效率的研究——兼论开源AI智能名片2+1链动模式S2B2C商城小程序的应用潜力
人工智能·小程序·自动驾驶
说私域1 天前
开源2+1链动模式AI智能名片S2B2C商城小程序:利用用户争强好胜心理促进分享行为的策略研究
人工智能·小程序·开源
css趣多多1 天前
认识小程序页面,小程序的宿主环境
小程序
说私域1 天前
对顾客行为的数据分析:融入2+1链动模式、AI智能名片与S2B2C商城小程序的新视角
人工智能·小程序·数据分析·开源