【小程序上传图片封装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);
      }
    });
  });
};
相关推荐
说私域2 小时前
定制开发开源AI智能名片驱动下的海报工厂S2B2C商城小程序运营策略——基于社群口碑传播与子市场细分的实证研究
人工智能·小程序·开源·零售
说私域8 小时前
内容力重塑品牌增长:开源AI大模型驱动下的智能名片与S2B2C商城赋能抖音生态种草范式
人工智能·小程序·开源·零售
Nueuis20 小时前
微信小程序前端面经
前端·微信小程序·小程序
轩1151 天前
实现仿中国婚博会微信小程序
微信小程序·小程序
2501_918941051 天前
旅游微信小程序制作指南
微信小程序·小程序·旅游
全职计算机毕业设计1 天前
SpringBoot+Mysql实现的停车场收费小程序系统+文档
spring boot·mysql·小程序
KerwinChou_CN2 天前
自由开发者计划 004:创建一个苹果手机长截屏小程序
图像处理·算法·智能手机·小程序
Uyker2 天前
空间利用率提升90%!小程序侧边导航设计与高级交互实现
前端·微信小程序·小程序
说私域2 天前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的生态农庄留存运营策略研究
人工智能·小程序·开源·零售
Nightne2 天前
小程序引入deepseek
小程序