【小程序上传图片封装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);
      }
    });
  });
};
相关推荐
熬耶5 小时前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
IT毕设实战小研8 小时前
基于Spring Boot校园二手交易平台系统设计与实现 二手交易系统 交易平台小程序
java·数据库·vue.js·spring boot·后端·小程序·课程设计
weixin_1772972206910 小时前
剧本杀小程序系统开发:重构推理娱乐生态
小程序·重构·娱乐
IT毕设实战小研1 天前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计
程序员陆通2 天前
零基础AI编程开发微信小程序赚流量主广告实战
微信小程序·小程序·ai编程
paopaokaka_luck2 天前
校园快递小程序(腾讯地图API、二维码识别、Echarts图形化分析)
vue.js·spring boot·后端·小程序·uni-app
头发还在的女程序员2 天前
ThinkPHP+Mysql 灵活用工小程序-技术深度解析与实践指南
数据库·mysql·小程序
编程猪猪侠2 天前
解决uni-app微信小程序编译报错:unexpected character `1`
微信小程序·小程序·uni-app
2501_915909062 天前
iOS 签名证书全生命周期实战,从开发到上架的多阶段应用
android·ios·小程序·https·uni-app·iphone·webview
suncentwl3 天前
论答题pk小程序软件版权的
小程序·答题小程序·答题pk·知识竞赛·答题pk软件