WeChat small program to achieve pdf,word and other format file upload

Keywords: Javascript

At present, support is only obtained from chat records.

I. Preface

At present, an interface is provided by wx.chooseMessageFile. It allows users to select one or more files from the chat record, and then returns some of its information, including the path address, file name and size of the file.

Access to these information, combined with the upload interface wx.uploadFile, can upload files.

 

2. Realization

First you need a button to call wx.chooseMessageFile.

 wx.chooseMessageFile({
      count: 1,     //Selectable number of files
      type: 'file',   //Can choose the type of file,I'm only allowed to upload files here..Also videos,picture,Or it could be
      success(res) { 
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].filename;
        var newfilename = filename + "";  
        
    if (size > 4194304||newfilename.indexOf(".pdf")==-1){ //I also limited the size and type of file.
          wx.showToast({
            title: 'File size cannot exceed 4 MB,The format must be pdf!',
            icon: "none",
            duration: 2000,
            mask: true
          })
        }else{
          that.setData({
          path: res.tempFiles[0].path, //Save the path of the file on the variable of the page,convenient wx.uploadFile call
          filename: filename              //Render to wxml It is easy for users to know what files they have chosen.
          })
        }
      }
    })

 

This saves the path and name of the file here.

 data: {
    path:'',
    filename:''
  },

Then when the user submits, the upload interface is invoked.

 wx.uploadFile({
                  url: serverUrl          //Upload Path
                  filePath: that.data.path,   //Just now data Saved file path
                  name: 'file',            //Background Acquisition Credentials
                  success() {          
                    wx.showToast({          //Do a hint or something else
                      title: '',
                      icon: "none",
                      duration: 5000,
                      mask: true,
                      success: function (res) {
                       
                      }
                    })
}
})

In this way, the preceding paragraph is completed and realized.

The file retrieved in the background is a temporary file at the end of. tmp

Then you can save the file to the location you want to save through the IO stream.

 

Three. Ending.

If you think this article is useful to you, don't forget to comment on it.

Posted by schoi on Sat, 05 Oct 2019 23:31:20 -0700