【小程序上传图片封装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);
      }
    });
  });
};
相关推荐
2601_9537208216 小时前
【计算机毕业设计】基于微信小程序的拼车服务系统设计与实现
微信小程序·小程序·课程设计
乐启国际旅行社有限公司18 小时前
文旅小程序性能优化:分包加载+地图视口懒加载解决景区卡顿与包超限
性能优化·小程序
万岳科技系统开发1 天前
校园跑腿外卖搭建助力高校周边商家拓展线上业务
大数据·人工智能·小程序
微三云 - 廖会灵 (私域系统开发)2 天前
消费返物业费平台搭建:美家时代商业模式拆解与系统开发选型指南
小程序·系统架构
greenbbLV2 天前
中小公司积分商城选型:SaaS与私有化方案对比解析
大数据·前端·小程序
2501_915909063 天前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张3 天前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势
android·汇编·ios·小程序·uni-app·cocoa·iphone
海纳百川·纳海川3 天前
租房行业数字化:换个思路解决“老问题”
大数据·微信小程序·小程序
上海云盾-小余3 天前
CC 高频请求 + DDoS 流量攻击实战防御:全链路 WAF 流量清洗部署完整流程
网络·爬虫·安全·小程序·ddos
2501_916008893 天前
iOS IPA文件反编译与打包操作方法,拆包分析防护和加固打包
android·macos·ios·小程序·uni-app·cocoa·iphone