React Native中如何将react-native-photo-editor返回的图片URI转为Base64编码
本地图片URI转Base64实现方案
你可以直接使用React Native原生支持的fetch API完成转换,无需额外安装第三方依赖,修改你的onDone回调逻辑即可:
核心转换代码
const uriToBase64 = async (uri) => { const response = await fetch(uri); const blob = await response.blob(); return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { resolve(reader.result); }; reader.onerror = reject; reader.readAsDataURL(blob); }); };
修改后的完整业务代码
const handleOnUploadFromLibrary = () => { launchImageLibrary(libraryOptions, async (response: ImagePickerResponse) => { if (response.assets) { let assets = response.assets[0]; let imagePathMinusExtention = assets.uri?.replace('file://', ''); setImagePickerAsset({...assets, uri: imagePathMinusExtention}); } PhotoEditor.Edit({ path: imagePickerAsset?.uri || '', onDone: async (path) => { console.log('donee::::'); let extention = "file://"; let imagePathPlusExtention = extention.concat(`${path}`); // 新增转Base64逻辑 const base64Image = await uriToBase64(imagePathPlusExtention); setImagePickerAsset({...imagePickerAsset, uri: imagePathPlusExtention}); var data: UsedAttachment = { fileType: imagePickerAsset?.type, fileName: imagePickerAsset?.fileName, refId: visit.draftAppRequestId, refTypeId: '5', //draftx title: imagePickerAsset?.fileName, mimeType: imagePickerAsset?.type, modelMapperKey: '', // 替换原有URI为Base64内容 files: [base64Image], }; callUploadAttachment({data}); hideDialog(); }, onCancel: () => { console.log('Cancel ::: '); hideDialog(); }, }); }); };
注意事项
- 如果你的API要求去掉Base64前缀(
data:image/png;base64,这类内容),可以在拿到reader.result后用split(',')[1]截取后半段即可 - 过大的图片转Base64会占用较多内存,建议先对图片做压缩处理再转换
内容的提问来源于stack exchange,提问作者Joyis
相关产品推荐
相关产品推荐

