WeChat applet uploads local files webview

We check the WeChat official documentation

You can select local files for pictures but the files are not allowed

Files only support uploading files in chat and do not allow mobile phones to select local files.

This does not meet our needs but we can achieve it through webview

What needs to be noted here is that we need to configure the URL to the domain name whitelist 

web-view | WeChat open document

Case use: WeChat applet vue project

 web page-vue settings:

Method 1: script finds index.html and writes jssdk

    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

 Method 2: Or npm download jsdk

npm install weixin-js-sdk --save
import wx from 'weixin-js-sdk'

Official start: Click the button to upload files in our web page to upload files. 

import { wxUploadFile } from '@/api/files'
..... 
 methods: {
    //这里就是正常的上传文件流的方法 wxUploadFile是后端给你的上传文件的地址请求
    uploadFile (info) {
      const { file } = info
      const formData = new FormData()
      formData.append('file', file)
      wxUploadFile(formData).then((res) => {
        //这里将上传后的文件信息 res 将调用jsdk 将文件信息res通过postMessage发回给小程序
        window.wx.miniProgram.postMessage({ data: res });
      })
    },
}
...
export function wxUploadFile (data, onUploadProgress = null) {
  const url ='http.....'//这里web上传文件的地址
  return axios({
    url,
    method: 'post',
    data,
    onUploadProgress,
    timeout: 60000,
  })
}

 Mini program settings:

settings-wxml:

The src here is the address of the uploaded file written on the web page (the address of the web page just now)

Mini program - js:

At this point we can get the uploaded file information

You can see that the applet has printed out the file information.

At this time, we can use the small program postMessage to obtain the two files just uploaded by e.detail in messages.

Guess you like

Origin blog.csdn.net/weixin_44383533/article/details/130822980