在开发移动应用时,经常需要实现用户从相册选择图片或直接拍照后上传至服务器的功能。本文将介绍如何使用 Uni-app 框架结合 JavaScript 来实现这一需求。

 创建上传管理器类

接下来,创建一个用于处理图片选择和上传的类 Uploader

class Uploader {
  // 构造函数
  constructor() {}

  // 选择图片
  choose(num) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: num,
        sourceType: ["camera", "album"],
        success(res) {
          resolve(res.tempFilePaths);
        },
        fail(err) {
          console.log(err);
          reject(err);
        },
      });
    });
  }

  // 上传单张图片
  upload_one(path, bizId, bizType) {
    return new Promise((resolve, reject) => {
      uni.showLoading({ title: "上传中" });

      uni.uploadFile({
        url: upload_img_url,
        filePath: path,
        name: 'file',
        formData: {
          bizId: bizId,
          bizType: bizType
        },
        header: {
          Authorization: "Bearer " + uni.getStorageSync("token"),
          "X-Requested-With": "XMLHttpRequest",
          Accept: `application/json, text/plain, */*`,
        },
        success: (uploadFileRes) => {
          const data = "string" === typeof uploadFileRes.data ? JSON.parse(uploadFileRes.data) : uploadFileRes.data;
          if (data.code === 200) {
            resolve(data.data);
          } else if (data.code === 401) {
            uni.navigateTo({ url: "/pages/login/login" });
            reject("401");
          }
        },
        fail(e) {
          console.log(e);
        },
        complete() {
          uni.hideLoading();
        },
      });
    });
  }

  // 上传多张图片
  upload(paths, bizId, bizType) {
    let num = paths.length;
    return new Promise(async (resolve, reject) => {
      let img_urls = [];
      for (let i = 0; i < num; i++) {
        let img_url = await this.upload_one(paths[i], bizId, bizType);
        img_urls.push(img_url);
      }
      resolve(img_urls);
    });
  }

  // 选择并上传
  choose_and_upload(bizId, bizType, num = 9) {
    return new Promise(async (resolve, reject) => {
      let paths = await this.choose(num);
      let img_urls = await this.upload(paths, bizId, bizType);
      let obj = { paths, img_urls };
      resolve(obj);
    });
  }
}

使用上传管理器

最后,实例化 Uploader 类,并调用其方法来完成图片的选择和上传。

let uploadPro = new Uploader();

// 示例用法
uploadPro.choose_and_upload('exampleBizId', 'exampleBizType', 5)
  .then(result => {
    console.log('Upload result:', result.img_urls);
  })
  .catch(error => {
    console.error('Error uploading:', error);
  });

通过上述步骤,你可以轻松地在 Uni-app 应用中实现图片选择与上传功能。