uniapp:图片、视频、音频文件上传

一、基本流程

图片、视频、音频的上传都是先通过uni的xx方法获取到临时路径,然后拿这个临时路径通过uni.uploadFile上传到公司的文件服务器中,返回文件路径

二、图片上传

图片使用uni.chooseMedia

js 复制代码
uni.chooseMedia({
  count: maxCount,
  mediaType: ["image"],
  sizeType: ["compressed"],
  camera: "back",
  success: (res) => {
    const tempFiles = res.tempFiles;
    const accept = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
    let fail = false;
    tempFiles.forEach((item, index) => {
      console.log("压缩之后的图片大小", item.size)
      const extension = item.tempFilePath
        .split(".")[1];
      if (accept.indexOf(extension) === -1 || Number(item.size) >
        Number(
          5242880) ||
        fileMap.imageUrls.length >= fileMap.maxSize
      ) {
        fail = true;
      } else {
        this.uploadFile(item, fileMap);
      }
    });
    if (fail) {
      uni.showToast({
        title: `仅支持照片文件,最大支持5M,最多传${fileMap.maxSize}张`,
        icon: "none",
        duration: 3000,
      });
    }
  },
});

uni.loadFile上传至文件服务器

js 复制代码
uploadFile(file, fileMap) {
  this.showLoading = true;
  // 以文件流的方式上传文件
  uni.uploadFile({
    url: config.baseUrl + '/common/uploadFile',
    filePath: file.tempFilePath || '',
    name: 'file',
    formData: {},
    headers: { 'Content-Type': 'multipart/form-data' },
    success: (uploadFileRes) => {
      this.showLoading = false;
      console.log('uploadFileRes>>',uploadFileRes);
      if (uploadFileRes && uploadFileRes.errMsg == 'uploadFile:ok') {
        let picItem = uploadFileRes && uploadFileRes.data ? JSON.parse(uploadFileRes.data) || {} : {}
        let url = picItem.data || ''
        const result = { data: {url} }
        this.addImageInfoEvt(fileMap, result) // 更新图片列表
      }
    },
    fail: (err) => {
      this.showLoading = false;
      console.log('图片上传接口调用失败', err)
    }
  })
}

三、视频上传

视频使用uni.chooseVideo

js 复制代码
chooseFile() {
  uni.chooseVideo({
    count: 1,
    sourceType: ["camera", "album"],
    maxDuration: 30,
    mediaType: ["video"],
    success: (res) => {
      if (res.size / 1024 / 1024 > 50) {
        return uni.showToast({
          icon: "none",
          title: "拍摄视频过大,请重新拍摄!",
        });
      }
      this.uploadFile(res);
    },
  });
}

uni.loadFile上传至文件服务器

js 复制代码
uploadFile(file) {
  uni.showLoading({ title: "努力加载中", mask: true });
  // 以文件流的方式上传文件
  uni.uploadFile({
    url: config.baseUrl + "/common/uploadFile",
    filePath: file.tempFilePath || "",
    name: "file",
    formData: {},
    headers: { "Content-Type": "multipart/form-data" },
    success: async (uploadFileRes) => {
      uni.hideLoading()
      console.log("uploadFileRes>>", uploadFileRes);
      if (uploadFileRes && uploadFileRes.errMsg == "uploadFile:ok") {
        const item =
          uploadFileRes && uploadFileRes.data
            ? JSON.parse(uploadFileRes.data) || {}
            : {};
        const params = {
          applyId: this.applyId,
          type: 1,
          VEDIO_SP: item.data,
        };
        const { flag } = await this.$api.investigate.addImageInfoCredit(
          params
        );
        if (flag) this.getImageInfoCredit();
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.log("图片上传接口调用失败", err);
    },
  });
}

四、音频上传

音频上传,微信小程序不支持,可以使用uni.chooseMessageFile,从聊天记录中选中音频上传

js 复制代码
chooseFile() {
  uni.chooseMessageFile({
    count: 1,
    extension: [".mp3"],
    success: (res) => {
      console.log("从聊天记录中获取文件", res);
      const { errMsg, tempFiles } = res;
      if (errMsg == "chooseMessageFile:ok" && tempFiles.length) {
        const { name, size, path } = tempFiles[0];
        console.log("临时文件", { size, path });
        if (name.slice(-4) != ".mp3") {
          return uni.showToast({
            icon: "none",
            title: "请上传mp3文件!",
            duration: 2000,
          });
        }
        if (size / 1024 / 1024 > 50) {
          return uni.showToast({
            icon: "none",
            title: "音频文件过大,请重新选择!",
          });
        }
        this.uploadFile(path);
      }
    },
  });
},

uni.loadFile上传至文件服务器

js 复制代码
uploadFile(path) {
  uni.showLoading({ title: "努力加载中", mask: true });
  // 以文件流的方式上传文件
  uni.uploadFile({
    url: config.baseUrl + "/common/uploadFile",
    filePath: path || "",
    name: "file",
    formData: {},
    headers: { "Content-Type": "multipart/form-data" },
    success: async (uploadFileRes) => {
      uni.hideLoading();
      console.log("uploadFileRes>>", uploadFileRes);
      if (uploadFileRes && uploadFileRes.errMsg == "uploadFile:ok") {
        const item =
          uploadFileRes && uploadFileRes.data
            ? JSON.parse(uploadFileRes.data) || {}
            : {};
        const params = {
          applyId: this.applyId,
          type: 1,
          VEDIO_LY: item.data,
        };
        const { flag } = await this.$api.investigate.addImageInfoCredit(
          params
        );
        if (flag) this.getImageInfoCredit();
      }
    },
    fail: (err) => {
      uni.hideLoading();
      console.log("图片上传接口调用失败", err);
    },
  });
}

4.1 音频播放

js 复制代码
  data() {
    return {
      audioUrls: [], // 音频列表
      innerAudioContext: null,
      currentIndex: "",
    };
  },
  onLoad(query) {
    this.getImageInfoCredit(); // 获取音频列表
    this.initInnerAudioContext();
  },
  onHide() {
    this.innerAudioContext && this.innerAudioContext.stop();
  },
  onUnload() {
    this.innerAudioContext && this.innerAudioContext.stop();
  },
    methods: {
    async getImageInfoCredit() {
      const params = { applyId: this.applyId, type: 1 };
      const { flag, data } = await this.$api.investigate.getImageInfoCredit(
        params
      );
      if (flag) {
        const list =
          data.VEDIO_LY.map((item) => ({ audio: item, icon: "play-circle" })) ||
          [];
        this.audioUrls = list;
      }
    },

    // 音频播放器初始化
    initInnerAudioContext() {
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.obeyMuteSwitch = false;
      this.innerAudioContext.sessionCategory = "playback";
      this.innerAudioContext.onPlay(() => {
        this.audioUrls = this.audioUrls.map((item, i) => ({
          ...item,
          icon: this.currentIndex == i ? "pause-circle" : "play-circle",
        }));
        uni.showToast({ icon: "none", title: "开始播放", duration: 2000 });
      });
      this.innerAudioContext.onPause(() => {
        this.audioUrls = this.audioUrls.map((item) => ({
          ...item,
          icon: "play-circle",
        }));
        uni.showToast({ icon: "none", title: "暂停播放", duration: 2000 });
      });
      this.innerAudioContext.onEnded(() => {
        this.audioUrls = this.audioUrls.map((item) => ({
          ...item,
          icon: "play-circle",
        }));
        uni.showToast({ icon: "none", title: "播放完成", duration: 2000 });
      });
      this.innerAudioContext.onError((res) => {
        uni.showToast({ icon: "none", title: "播放错误", duration: 2000 });
        console.log("错误", res.errMsg);
        console.log("错误", res.errCode);
      });
    },

    handlePlay(item, index) {
      this.innerAudioContext.src = item.audio;
      if (item.icon == "play-circle") {
        // 暂停时,继续播放
        this.innerAudioContext.play();
        this.currentIndex = index;
      } else {
        // 正在播放时,暂停播放
        this.innerAudioContext.pause();
      }
    },
  }
相关推荐
工业互联网专业1 小时前
毕业设计选题:基于ssm+vue+uniapp的捷邻小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计
全职计算机毕业设计5 小时前
基于 UniApp 平台的学生闲置物品售卖小程序设计与实现
android·uni-app
涔溪5 小时前
uni-app环境搭建
前端·uni-app
遛马5 小时前
uni-app安装插件
uni-app
清云随笔8 小时前
uniapp|微信小程序 实现输入四位数 空格隔开
uni-app
一只欢喜10 小时前
uniapp使用uview2上传图片功能
前端·uni-app
ggome10 小时前
Uniapp低版本的安卓不能用解决办法
前端·javascript·uni-app
贰叁!18 小时前
uniapp输入车牌号组件
uni-app
她似晚风般温柔78920 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app
Jiaberrr21 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app