微信小程序 选择图片 并上传到服务器

官方地址:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html

选择图片以后,实际上图片的本地地址:

http://tmp/rac1Gf3dvoNb27bf6bd54e09ef16b995c575fde40c8f.jpeg

这个看上去怪怪的,因为本地并没有这样的地址,不用管它,这个小程序能够读到就可以。

wx.chooseImage({
  success (res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success (res){
        const data = res.data
        //do something
      }
    })
  }
})

看一下服务器演示代码:

@PostMapping("/upload")
    public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
        Map<String, Object> resultMap = new HashMap<>();

        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        String strNewFileName = 
        ...
        file.transferTo(new File(folder, strNewFileName));
        ...
}

这个随便找一下spring boot上传文件的代码就可以。

微信小程序上传图片,比想象中要简单的多。

道法自然
原文地址:https://www.cnblogs.com/jiduoduo/p/14778253.html