微信小程序下载网络图片保存到本地

微信小程序下载网络图片保存到本地

问题背景

前一篇文章介绍了,微信小程序网络请求数据并在页面列表显示(参考 https://blog.51cto.com/baorant24/6189453 ),本文将介绍微信小程序是如何获取网络图片并保存到本地的。

问题分析

关键环节分析如下:

(1)微信小程序判断目录/文件是否存在 FileSystemManager.access(Object object),参考官方文档( https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.access.html ),示例代码如下:

const fs = wx.getFileSystemManager()
// 判断文件/目录是否存在
fs.access({
  path: `${wx.env.USER_DATA_PATH}/hello.txt`,
  success(res) {
    // 文件存在
    console.log(res)
  },
  fail(res) {
    // 文件不存在或其他错误
    console.error(res)
  }
})

// 同步接口
try {
  fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
} catch(e) {
  console.error(e)
}

(2)FileSystemManager.access 的同步版本 FileSystemManager.accessSync(string path),参考官方文档( https://developers.weixin.qq.com/miniprogram/dev/api/file/FileSystemManager.accessSync.html ),示例代码如下:

const fs = wx.getFileSystemManager()
// 判断文件/目录是否存在
fs.access({
  path: `${wx.env.USER_DATA_PATH}/hello.txt`,
  success(res) {
    // 文件存在
    console.log(res)
  },
  fail(res) {
    // 文件不存在或其他错误
    console.error(res)
  }
})

// 同步接口
try {
  fs.accessSync(`${wx.env.USER_DATA_PATH}/hello.txt`)
} catch(e) {
  console.error(e)
}

(3)获取图片信息。网络图片需先配置download域名才能生效。 wx.getImageInfo(Object object),参考官方文档( https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.getImageInfo.html ),示例代码如下:

wx.getImageInfo({
  src: 'images/a.jpg',
  success (res) {
    console.log(res.width)
    console.log(res.height)
  }
})

问题解决

话不多说,直接上代码。

(1)index.js文件,代码如下:

// pages/healdata/healthydata.ts
Page({
  /**
   * 页面的初始数据
   */
  data:{
    code:"0",
    location:[],
    imageUrl: "https://profile-avatar.csdnimg.cn/default.jpg!0"
  },

  /* 保存图片 */
  save_photo: function () {
    const fs = wx.getFileSystemManager()
    var isExist = false; //目录是否存在
    var that = this;
    // 同步接口,判断路径是否存在
    try {
      fs.accessSync(`${wx.env.USER_DATA_PATH}/photoinvoice/1553115`)
      isExist = true;
    } catch (e) {
      console.error(e)
    }

    if (isExist != true) {
      // 同步接口,创建目录
      try {
        fs.mkdirSync(`${wx.env.USER_DATA_PATH}/photoinvoice/1553115`, true)
        console.log('mkdirSync')
      } catch (e) {
        console.error(e)
      }
    }
    console.log('USER_DATA_PATH: ' + `${wx.env.USER_DATA_PATH}/photoinvoice/1553115`)
    console.log('imageUrl: ' + that.data.imageUrl)

    // 获取图片
    wx.getImageInfo({
      src: this.data.imageUrl,
      success: function (res) {
        var path = res.path;
        console.log("path: " + path) 
        var startPos = path.lastIndexOf("//");
        console.log(startPos)
        var picName = path.slice(startPos + 2, path.length); //加2是为了从//后面截取。所以+2,把//过滤掉
        console.log("picName " + picName)
        fs.saveFile({
          tempFilePath: path,
          filePath: `${wx.env.USER_DATA_PATH}/photoinvoice/1553115/${picName}`, //保存的时候必须跟上路径和文件名
          success: function (res) {
            console.log("保存成功")
            console.log(res)
          },
          fail: function (res) {
            console.log("保存失败")
            console.log(res)
          }
        })
      }
    })
  },
})

(2)index.wxml文件,代码如下:

<view>
  <button class="buttonStyle" type="primary" bindtap="save_photo">请求网络</button>
  <view>结果返回:{{code}}</view>
</view>

(3)index.wxss文件,代码如下:

/* 设置swiper组件的宽高 */
.swiper{
  width: 100%;
  height: 600rpx;
}
/* 设置swiper组件里面图片的宽高 */
.image{
  width: 100%;
  height: 600rpx;
}

.content1{
  /* text-align: center; */
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin: 10rpx;
}

.buttonStyle{
  margin-top: 120rpx;
}

.place{
  font-style: italic;
}

模拟器运行结果如下: image.png 保存文件到本地系统目录失败,报错: "saveFile:fail no such file or directory http://usr/photoinvoice/1553115/tmp/9UXFbyUvzCtwc7bc5bf164499999108eb505ceca5952.png"。

解决方案: 切换到真机测试

运行结果如下: image.png

问题总结

本文介绍了微信小程序是如何获取网络图片并保存到本地的,有兴趣的同学可以进一步深入研究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值