解决uni-app在App端上传图片时路径转Base64的问题

本文介绍了一种在uni-app中将图片路径转换为Base64字符串的方法,通过使用image-tools插件实现,解决了前端上传图片时路径与后端需求不匹配的问题。

在用uni-app开发项目的时候大家都会遇到这么一个问题,
就是上传图片时在App上拿到的是文件路径,
然而后端要接收的却是Base64字符串,
这就尴尬了,在App端又无法调用Web Api(例如:Blob fileReader 等),
自己写插件的话又很麻烦,因此我找了很久才找到下面这个可以直接将Path转为Base64的插件。

image-tools

npm安装

npm i image-tools --save

文件内引入

import { pathToBase64, base64ToPath } from 'image-tools'

pathToBase64
从图像路径转换为base64,uni-app、微信小程序和5+APP使用的路径不支持网络路径,如果是网络路径需要先使用下载API下载下来。

pathToBase64(path).then(base64 => {
    console.log(base64)
})
.catch(error => {
    console.error(error)
})

base64ToPath
将图像base64保存为文件,返回文件路径。

base64ToPath(base64).then(path => {
    console.log(path)
})
.catch(error => {
    console.error(error)
})

可以利用promise来串行和并行的执行多个任务

// 并行
Promise.all(paths.map(path => pathToBase64(path)))
  .then(res => {
    console.log(res)
    // [base64, base64...]
  })
  .catch(error => {
    console.error(error)
  })
// 串行
paths.reduce((promise, path) => promise.then(res => pathToBase64(path).then(base64 => (res.push(base64), res))), Promise.resolve([]))
  .then(res => {
    console.log(res)
    // [base64, base64...]
  })
  .catch(error => {
    console.error(error)
  })

插件地址:https://www.npmjs.com/package/image-tools

评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦一场江南烟雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值