主要是为了处理问题
targetSdkVersion设置>=29后在Android10+系统设备不支持当前路径。请更改为应用运行路径!具体请看:https://ask.dcloud.net.cn/article/36199
async function path2Base64(path: string) {
// 通过 UniAPP提供的方法把原始图片路径转为临时图片路径
const localPath = await new Promise((resolve, reject) => {
uni.compressImage({
src: path,
quality: 100,
success: res => {
resolve(getLocalFilePath(res.tempFilePath));
},
fail: e => {
reject('compressImage:e', e);
},
});
});
const base64: string = await new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
getLocalFilePath(path),
function (entry) {
(entry as any).file(
function (file) {
var fileReader = new plus.io.FileReader();
fileReader.onload = function (data: any) {
resolve(data.target.result);
};
fileReader.onerror = function (e) {
console.error('FileReader:e', e);
reject(e);
};
fileReader.readAsDataURL(file);
},
function (e) {
console.error('entry:e', e);
reject(e);
}
);
},
function (e) {
console.error('resolveLocalFileSystemURL:e', e);
reject(e);
}
);
});
return base64;
}
function getLocalFilePath(path: string) {
if (
path.indexOf('_www') === 0 ||
path.indexOf('_doc') === 0 ||
path.indexOf('_documents') === 0 ||
path.indexOf('_downloads') === 0
) {
return path;
}
if (path.indexOf('file://') === 0) {
return path;
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path;
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path);
if (localFilePath !== path) {
return localFilePath;
} else {
path = path.substr(1);
}
}
return '_www/' + path;
}
示例
uni.chooseImage({
success: async res => {
try {
const { tempFilePaths } = res;
const filePaths = typeof tempFilePaths !== 'string' ? tempFilePaths : [tempFilePaths];
const base64Arr: string[] = [];
for (const path of filePaths) {
const base64 = await path2Base64(path);
base64Arr.push(base64);
}
} catch (e) {
console.log('chooseImage:e', e);
}
},
});