2022-11-28 记录uniapp+小程序项目 如何上传excel、word、图片文件

这里直接用到微信提供的api:wx.chooseMessageFile

示例:


  wx.chooseMessageFile({
    count: 1,
    success: (res) => {
      const tempFilePaths = res.tempFiles;
      if (tempFilePaths[0].path.indexOf(".docx") > -1) {
      uni.uploadFile({
        url: '你的接口地址',
        filePath: tempFilePaths[0].path,
        name: "file",
        formData: {
          token: '123', // 这里是传给后端的参数,我这里随便写的,你可以根据业务来安排
        },
        success: (res) => {
          const req = JSON.parse(res.data);
          alert(req.msg);
        },
        fail: (err) => {
          console.log("出错了");
          console.log(err);
          alert("上传失败");
        },
      });
     
      } else {
        app.alert("请选择docx文件进行上传");
      }
    },
  });

这里我对上传的文件进行了限制,如果选中的文件不是.docx后缀结尾的,就不允许上传,实际上,wx.chooseMessageFile允许所有文件类型上传,excel、word、图片不在话下。

我这里是对word上传进行了限制,不需要可以去掉。

uniapp上传接口(非图片、视频类)uni.chooseFile不支持小程序端,仅支持H5端,并且人家官方也说明了可以用微信的api,所以wx.chooseMessageFile是不二选择。

posted @ 2022-11-28 14:43  叶乘风  阅读(2077)  评论(0编辑  收藏  举报