微信小程序获取POST接口的文件或图片

2,915 阅读1分钟

多数情况下,小程序的图片直接设置Image组件的src路径即可。某些特殊的场景下,后台同学是通过post接口返回满足特定条件的文件或者图片。wx.downloadFile似乎搞不了post,request一波,撸篇短文,记录一下挖了两小时的坑。

模拟接口

用express模拟POST的图片接口,看👇,摸鱼时间紧迫,随便写一下。

    const express = require('express')
    const fs = require('fs')
    
    const app = new express()
    
    app.post('/image', function(req, res) {
      res.set('Content-Type', 'image/png')
      let rs = fs.createReadStream('./test.png')
      rs.pipe(res)
    })
    
    app.listen(3000)

请求文件

wxml:

    <image class="post-image" src="{{imageURL}}" mode="cover"></image>

js:

wx.request({
      url: 'http://localhost:3000/image',
      responseType: 'arraybuffer',
      method: 'POST',
      success: res => {
        this.setData({
          imageURL: 'data:image/png;base64, ' + wx.arrayBufferToBase64(res.data)
        })
      }
    })

前面一直获取不到正确的arrayBuffer卡了一阵,用arrayBufferToBase64发现是空的。转了两圈微信开发者社区,也没啥头绪,发现typeof res.datastring, 于是猜测返回的data被转换了wx.request转换了。查看文档发现responseType: 'arraybuffer',加上获取到正确的文件流数据。

存图片

也可以用writeFile,存起来备用

wx.request({
      url: 'http://localhost:3000/image',
      responseType: 'arraybuffer',
      method: 'POST',
      success: res => {
        let fsm = wx.getFileSystemManager()
        fsm.writeFile({
          filePath: `${wx.env.USER_DATA_PATH}/test.png`,
          encoding: 'binary',
          data: res.data,
          success: res => {
            this.setData({
              imageURL: `${wx.env.USER_DATA_PATH}/test.png`
            })
          }
        })
      }
    })

溜了溜了,搬砖去了~~~~~~~~~~~(写的简陋,勿喷)