uniapp WeChat applet uploads pictures & files and supports picture and file preview (pdf and other file previews) for detailed teaching!

First of all, there are several ways to open PDF and other files in the applet:

  1. Use wx.downloadFile() + wx.openDocument() that comes with WeChat
  2. Using web-view, webview in uni-app can directly load pdf files
  3. You can use pdf.js mentioned on the Internet to achieve this (I have not used this, so I will not introduce it)

A lot of information found on the Internet shows that Android can be opened through the first method above, but iOS cannot be opened using the first method. This is true on the Internet and in the community, but it seems that the bug has been fixed. After testing, it is now available on both Android and iOS. can be opened.

If you encounter such a bug, you can use method 1 on Android and webview on Apple to open the file.

I upload files using the uni-ui upload component:

A bug to mention here is that after this component sets v-model and uploads the file, logically the value of the v-model read should be the previously uploaded file data. However, there is no data after printing, but only after printing. After clicking to delete the file, the v-model will have a value after reading it. This bug has been raised in the community a long time ago, so I manually store the file data by listening to the select event, and then delete the corresponding data in the array in response to the delete event. File data. Secondly, because the requirement in my project is to click on the file name to preview, then the file display is handwritten. I used display: none to hide the original file display of the component.

<view style="width: 70%;margin: 0 auto;margin-bottom: 20rpx;">
        <uni-file-picker v-model="fileList" title="最多选择9个文件" :list-styles="styleObject" :sourceType="['album', 'camera']"
          file-mediatype="all" ref="files" :limit="11" :auto-upload="false" @select="select" @success="success"
          @fail="fail" @progress="progress" @delete="deleteFile">
          <view class="clickBtn">点击选择文件</view>
        </uni-file-picker>
      </view>
      <view style="width: 70%;margin: 0 auto;margin-bottom: 20rpx;" v-for="(item, index) in ajaxFileList" :key="index">
        <view class="flex justify-start align-center">
          <view class="fileBox" @click="Preview(item)">{
   
   { item.name }}</view>
          <view class="delBox" @click="delFile(index)">删除</view>
        </view>
      </view>
 // 获取上传状态
    select(e) {
      console.log('选择文件:', e)
      e.tempFiles.forEach(item => {
        this.ajaxFileList.push({//用一个变量单独存储上传的文件数据
          name: item.cloudPath,
          extname: item.extname,
          url: item.path,
        })
      });
      console.log(this.ajaxFileList);
    },
    deleteFile(e) {
      console.log('删除文件:', e)
      this.ajaxFileList.forEach((item, index) => {
        if (e.tempFilePath === item.path) {
          this.ajaxFileList.splice(index, 1)
        }
      })
      console.log(this.ajaxFileList);
    },
    // 上传成功
    success(e) {
      console.log('上传成功')
    },
    // 上传失败
    fail(e) {
      console.log('上传失败:', e)
    },
    // 获取上传进度
    progress(e) {
      console.log('上传进度:', e)
    },
    Preview(item) {//用正则去识别不同文件类型,然后对应不同文件类型去做不同操作
      console.log(item);
      // 定义图片类型的正则表达式
      const imageRegex = /(\.jpg|\.jpeg|\.png)$/i;
      // 定义文档类型的正则表达式
      const docRegex = /(\.doc|\.docx|\.pdf)$/i;
      // 定义其他文件类型的正则表达式
      const othersRegex = /(\.txt|\.csv|\.xlsx)$/i;
      // 利用正则表达式判断文件类型
      if (imageRegex.test(item.name)) {
        console.log("图片类型");
        this.lookImage(item.url)
      } else if (docRegex.test(item.name)) {
        console.log("文档类型");
        this.lookFile(item.url)
      } else if (othersRegex.test(item.name)) {
        console.log("其他文件类型");
      } else {
        uni.showToast({
          title: `未知文件类型`,
          icon: 'none',
          duration: 2000
        })
      }
    },
    delFile(index) {
      console.log(index);
      this.ajaxFileList.splice(index, 1)
    },
    lookImage(url) {
      let imgArray = [];
      imgArray[0] = url
      uni.previewImage({
        current: 0,
        urls: imgArray
      })
    },
    lookFile(url) {
    
      uni.openDocument({
        filePath: url,
        success: function (res) {
          console.log("打开文档成功");
        },
        fail: function (res) {
          console.log("uni.openDocument,fail");
          console.log(res)
        },
        complete: function (res) {
          console.log("uni.openDocument,complete");
          console.log(res)
        }
      });
    },

If your files are https or http online resources:

uni.downloadFile({
        url: url,
        success: function (res) {
          var filePath = res.tempFilePath;
          console.log("下载文件:",res);
          uni.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log("打开文档成功");
            },
            fail: function (res) {
            console.log("uni.openDocument,fail");
            console.log(res)
          },
          complete: function (res) {
            console.log("uni.openDocument,complete");
            console.log(res)
          }
          });
        },
        fail: function (res) {
        console.log('uni.downloadFile,fail')
        console.log(res)
      },
      complete: function (res) {
        console.log('uni.downloadFile,complete')
        console.log(res)
      }},
      );

The requirement I encountered this time was to support previewing files when previewing single images and uploading files.

If there is a situation where uni.openDocument can be opened on Android but cannot be opened on iOS, then read the following article.

https://blog.csdn.net/weixin_38673922/article/details/128626373

https://blog.csdn.net/liuxiaocaie/article/details/125874472

Guess you like

Origin blog.csdn.net/m0_57033755/article/details/134594459