uni-app 提供了很多图片处理的Api,比如 uni.chooseImage()方法,但基本都是本地、拍照上传,本地临时、持久存储,要想跟服务端交互,就需要使用上传Api uni.uploadFile()。但项目需求是想将图片转为base64格式后上传,经多方查找,找到了微信提供的Api方法 wx.getFileSystemManager()。
wx.getFileSystemManager
wx.FileSystemManager.readFile() 方法可以根据提供的本地文件路径来读取本地文件内容,这正好符合项目需求,查看 uni-app Api 文档,也有实现这个方法 uni.FileSystemManager.readFile() ,但不知是否已经支持。经体验版测试,功能效果跟微信Api一致。
/*
* 上传头像
* 注:使用vscode编辑器时,会有报错提醒,可忽略
*/
public chooseImage(): any {
if (this.state) {
return false;
}
this.state = true;
uni.chooseImage({
count: 1,
sizeType: 'compressed',
success: (res: any) => {
this.state = false;
if (res.tempFiles[0].size >= 200000) {
uni.showToast({ title: '请上传低于200K的图片', icon: 'none', duration: 2000 });
return false;
}
uni.compressImage({
src: res.tempFilePaths[0],
quality: 0,
success: (res) => {
uni.getFileSystemManager().readFile({
filePath: res.tempFilePath, // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: async (res: any) => {
this.userInfoData.headImg = 'data:image/png;base64,' + res.data;
}
});
}
});
},
fail: (err: Error) => (this.state = false)
});
}