WeChat applet - download files to local, open documents

foreword

Requirement scenario description: The interface obtains the file address of the server, and then downloads the file to the local mobile phone in the applet. According to the file format, the download type is divided into the following four situations:

  • Download pictures to local
  • Download video to local
  • Open document, supported formats: doc, xls, ppt, pdf, docx, xlsx, pptx
  • Download audio to local, and other format files

accomplish

  • Download pictures to album: saveImageToPhotosAlbum()
  • Download video to album: saveVideoToPhotosAlbum()
  • Open the document: openDocument()
  • Download audio to local: FileSystemManager file manager, alternatives.

Specific demo code

1. Download the picture to the local

onSavePic() {
  // #ifdef MP-WEIXIN
  uni.getImageInfo({
    src: _this.imageUrl, // 图片下载网络地址
    success: function(e) {
      // e.type=png/jpg 扩展名
      // filePathNew: 指定文件下载后存储的路径 (本地路径)
      var filePathNew = wx.env.USER_DATA_PATH + "/" + new Date().valueOf() +'.'+e.type; 
      uni.downloadFile({
        url: _this.imageUrl, 
        filePath: filePathNew,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: filePathNew,
              success: function() {
                uni.showToast({title: '保存到相册成功'});
              },
              fail: function(err){}
            });
          }
        }
      });
    },
    complete: function(e) {}
  });
  // #endif
},

2. Download the video to local

The implementation method is the same as downloading pictures, except that the saveVideoToPhotosAlbum() method needs to be used to save the video.

onSaveVideo() {
  // #ifdef MP-WEIXIN
  uni.downloadFile({
    url: this.videoUrl, 
    success: (data) => {
      if (data.statusCode === 200) {
        uni.saveFile({
          tempFilePath: data.tempFilePath, //临时路径
          success: function(res) {
            uni.saveVideoToPhotosAlbum({
              filePath: res.savedFilePath,
              success:function(){
                uni.hideLoading()
                uni.showToast({title:"保存到相册成功"})
              }
            })
          }
        });
      }
    },
    fail: (err) => {
      uni.showToast({title: '失败请重新下载'});
    },
  });
  // #endif
},

3. Open the document , supported formats: doc, xls, ppt, pdf, docx, xlsx, pptx

onOpenDocment() {
  uni.downloadFile({
    url: this.fileUrl,// 网络文档地址
    success: (data) => {
    if (data.statusCode === 200) {
        uni.saveFile({
          tempFilePath: data.tempFilePath, //临时路径
          success: function(res) {
            // 保存路径
            uni.showToast({ title: "文件已保存:"+res.savedFilePath,duration:3000 })
            setTimeout(()=>{
              //打开文档查看
              uni.openDocument({
                filePath:res.savedFilePath,
                success:function(res){
                  console.log('打开文档成功')
                }
              })
            }, 3000);
          }
        });
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '失败请重新下载'
      });
    },
  });
},

4. Download audio.

Due to the limitations of the WeChat platform, except for videos and pictures that support downloading files to the local, and some document formats that support direct opening, files in other formats do not support downloading files to the local.

On the official website of the WeChat applet, it is mentioned that you can use the FileSystemManager file manager to download files in other formats such as audio.

Download files using the FileSystemManager file manager,

Documents are mainly divided into two categories:

  • Code package files: Code package files refer to files added in the project directory.
  • Local file: a file generated locally by calling the interface, or downloaded through the network, and stored locally.

There are three types of local files:

  1. Local temporary files: files that are generated temporarily and will be recycled at any time. It can store up to 4GB when running. After running, if more than 2GB has been used, it will take the file as the dimension and clean up according to the latest usage time from far to near to less than 2GB.
  2. Local cache file: the file generated after the applet caches local temporary files through the interface, and the directory and file name cannot be customized. Together with local user files, mini-programs (including mini-games) can store up to 200MB.
  3. Local user files: the files generated by the applet after caching local temporary files through the interface, allowing to customize the directory and file name. Together with the local cache files, mini-programs (including mini-games) can store up to 200MB.

Local user files: A user file directory is provided for developers, and developers have completely free read and write permissions to this directory. wx.env.USER_DATA_PATH The path to this directory can be obtained by  . The path resolved to the phone is wxfile://usr/, the real path: phone/internal storage/tencent/MicroMsg/wxanewfiles/xxxx/abc.mp3.

xxxx: It is a very long folder composed of English numbers. The clear rules of this folder are not clear yet. So the specific path of the saved file is not known. Moreover, the Apple mobile phone cannot obtain the file path inside WeChat. So this way pass.

If you want to realize the function of downloading audio, you can only find an alternative.

Solution 1: Download the file and save it as an image format. After saving successfully, change the extension. The implementation steps are as follows:

① After using wx.downloadFile to download the mp3 file, use FileSystemManager.save to save the mp3 file as an image format.

② After saving successfully, use wx.saveImageToPhotosAlbum to save to the album, and the final path is: phone/internal storage/tencent/MicroMsg/WeiXin/mmexport1xxxxxx.jpg. 1xxxxxx is the timestamp, which file can only be judged based on the file generation time. 

This method is cumbersome and not suitable for users. pass

Solution 2: Copy the audio network address, open the system browser, and download the audio in the browser. The pro-test is effective.

Apple mobile phone :
      ①. When using the safari browser to download, click the share button in the tab below and select the option: 'Save to "File"' to save it to the "File" management of the mobile phone. Renaming is not supported.
      ②. When using QQ browser, audio can only be played in the browser, but cannot be downloaded.

Android phone :
      ①. Open the link in the browser, you can download it directly, and support renaming.

The method of copying the network address to the clipboard is as follows:

// 下载音频到本地
onSaveAudio() {
  uniCopy({
    content:this.audioUrl,// 音频下载链接
    success:(res)=>{
      uni.showToast({title: res})
    },
    error:(e)=>{
      uni.showToast({title: e,})
    }
  })
},
uniCopy({content,success,error}) {
  if(!content) return error('复制的内容不能为空 !')
  content = typeof content === 'string' ? content : content.toString() // 复制内容,必须字符串,数字需要转换为字符串
  /**
   * 小程序端 和 app端的复制逻辑
   */
  //#ifndef H5
  uni.setClipboardData({
    data: content,
    success: function() {success("复制成功~")},
    fail:function(){success("复制失败~")}
  });
  //#endif
  
  /**
   * H5端的复制逻辑
   */
  // #ifdef H5
  if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
    // 不支持
    error('浏览器不支持')
  }
  let textarea = document.createElement("textarea")
  textarea.value = content
  textarea.readOnly = "readOnly"
  document.body.appendChild(textarea)
  textarea.select() // 选择对象
  textarea.setSelectionRange(0, content.length) //核心
  let result = document.execCommand("copy") // 执行浏览器复制命令
  if(result){
    success("复制成功~")
  }else{
    error("复制失败,请检查h5中调用该方法的方式,是不是用户点击的方式调用的,如果不是请改为用户点击的方式触发该方法,因为h5中安全性,不能js直接调用!")
  }  
  textarea.remove()
  // #endif
},

5. Download files in other formats. Similar to downloading audio, it will be added when there is time.

Notice:

The address of the download resource. Before downloading, you must set the downloadFile legal domain name of the server domain name in the development settings of the WeChat public platform. The resource address must come from a legal domain name before it can be requested.

7834b0e9bdd146999a16cc53ac3739d1.png

PS: To save pictures and videos to the album, you need to obtain permission to save them, and the process of obtaining permission

PS: *.unknown error and saveImageToPhotosAlbum: fail invalid file type error occurred when saving pictures to the album

Guess you like

Origin blog.csdn.net/loveliqi/article/details/125370839