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

11,005 阅读3分钟

一、基本流程

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

二、图片上传

图片使用uni.chooseMedia

const maxCount = fileMap.imageUrls ? fileMap.maxSize - fileMap.imageUrls.length : fileMap.maxSize; // 限制最多可以选择的图片张数

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上传至文件服务器

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) || {} : {}
        if (picItem.errCode == -1) {
          let url = picItem.data || ''
          const result = { data: {url} }
          this.addImageInfoEvt(fileMap, result) // 更新图片列表
        } else {
          uni.showToast({
            icon: 'error',
            title: picItem.errMsg || '文件上传失败,请重试'
          })
        }
      }
    },
    fail: (err) => {
      this.showLoading = false;
      console.log('图片上传接口调用失败', err)
    }
  })
}

三、视频上传

视频使用uni.chooseVideo

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上传至文件服务器

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,从聊天记录中选中音频上传

image.png

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上传至文件服务器

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 音频播放

效果:

动画.gif

  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) => {
        if(res.errCode != -1) uni.showToast({ icon: "none", title: "播放错误", duration: 2000 }); // 手机上从小程序回到主页面,再次进入到小程序时,会触发onError,错误码是-1,这种情况不需要弹出播放错误的提示
        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();
      }
    },
  }

音频播放在微信开发者工具中没有问题,到真机上(安卓)播放不了,可以试试使用uni.downloadFile

    data中设置一个audioList数组用来存放解析后的文件
    
    
    
    handlePlay(item, index) {
      if (item.icon == "play-circle") {
        if (this.audioList[index]) {
          this.innerAudioContext.src = this.audioList[index];
          // 暂停时,继续播放
          this.innerAudioContext.play();
          this.currentIndex = index;
        } else {
          uni.showLoading({ title: "解析文件中", mask: true });
          uni.downloadFile({
            url: item.audio,
            success: (res) => {
              console.log("成功", res);
              if (res.statusCode == 200) {
                uni.hideLoading();
                this.innerAudioContext.src = res.tempFilePath;
                this.audioList[index] = res.tempFilePath;
                // 暂停时,继续播放
                this.innerAudioContext.play();
                this.currentIndex = index;
              }
            },
          });
        }
      } else {
        // 正在播放时,暂停播放
        this.innerAudioContext.pause();
      }
      
      // this.innerAudioContext.src = item.audio;
      // if (item.icon == "play-circle") {
      //   // 暂停时,继续播放
      //   this.innerAudioContext.play();
      //   this.currentIndex = index;
      // } else {
      //   // 正在播放时,暂停播放
      //   this.innerAudioContext.pause();
      // }
    },

除了uni.downloadFile,还可以试试 wx.createAudioContext('myAudio2') ,DOM中需要添加,当uni.createInnerAudioContext()播放不了时,在onError事件中监听,使用wx.createAudioContext,这个方法已经不维护了

          this.innerAudioContext.onError((error) => {
            console.log("error", error)
            this.audioContext = wx.createAudioContext('myAudio2')
            this.audioContext.play()
          })

或者使用audio标签播放,同样地,微信也是不维护audio标签了,推荐使用createInnerAudioContext


            <audio
              style="text-align: left"
              :src="item.audio"
              poster="https://www.hfkxjf.com/lydev/fins-appzhany/base/downloadFile?fastDfsUrl=iNRJ4KmH0Qt9DoURdo2DQNUv1FhGdNRTO6dpOlHF2YQrOjG/1f7yE5uBu2HU/1a38E2J4gZ/7c2lTeVRj+ItrHJpXvex7D1P54m3YCkFTzw="
              :name="'音频' + index"
              :author="'作者' + index"
              :action="{ method: 'pause' }"
              controls
            ></audio>

如果你觉得这篇文章对你有用,可以看看作者封装的库xtt-utils,里面封装了非常实用的js方法。如果你也是vue开发者,那更好了,除了常用的api,还有大量的基于element-ui组件库二次封装的使用方法和自定义指令等,帮你提升开发效率。不定期更新,欢迎交流~