gpt4 book ai didi

react-native - 如何使用expo从文件系统读取jpg文件?

转载 作者:行者123 更新时间:2023-12-03 21:20:44 24 4
gpt4 key购买 nike

我使用以下代码使用 expo 下载了一个图像(a.jpg):

 FileSystem.downloadAsync(
httpUrl,
FileSystem.documentDirectory + location
).then((result)=>{
const uri = result.uri;
}).catch((err)=>{
console.log("​getFile -> err", err);}
);

文件成功保存在文件系统中。稍后当我尝试读取文件时,出现无法读取文件的错误。用于读取文件的代码:
const fileInfo = await FileSystem.getInfoAsync(uri);
if(fileInfo.exists){
FileSystem.readAsStringAsync(uri).then(data => {
const base64 = 'data:image/jpg;base64' + data;
resolve(data) ;
}).catch(err => {
console.log("​getFile -> err", err);
reject(err) ;
});
}

上面的代码返回无法读取文件的错误。 fileInfo.exists 为真,因为文件存在于文件系统中。
 ​getFile -> fileInfo Object {
"exists": 1,
"isDirectory": false,
"modificationTime": 1547272322.8714085,
"size": 51725,
"uri": "file:///Users/deeparora/Library/Developer/CoreSimulator/Devices/A2DC4519- C18C-4512-8C23-E624A1DAA506/data/Containers/Data/Application/6D7B23AA- A555-4F9A-B9D1-EB5B9443CCB6/Documents/ExponentExperienceData/ %2540anonymous%252Fhola-vet-6faee8ac-e309-4d5b-a1c0-6f8688f8a508/a.jpg",
:}

读取文件时出错:
err [Error: File 'file:///Users/deeparora/Library/Developer/CoreSimulator/Devices/A2DC4519-C18C-4512-8C23-E624A1DAA506/data/Containers/Data/
Application/6D7B23AA-A555-4F9A-B9D1-EB5B9443CCB6/
Documents/ExponentExperienceData/%2540anonymous%252Fhola-vet-6faee8ac-e309-4d5b-a1c0-6f8688f8a508/a.jpg' could not be read.]

如果我尝试读取文本文件(a.json)而不是 jpg(a.jpg),则一切正常。因此, FileSystem.readAsStringAsync 适用于文本文件,不适用于 jpg。可能需要提供其他参数作为此方法的选项,以便将 jpg 读取为 base64 字符串。

最佳答案

这是因为你没有告诉 FileSystem.readAsStringAsync您需要的编码类型是 base64。

尝试使用

let options = { encoding: FileSystem.EncodingTypes.Base64 };
FileSystem.readAsStringAsync(uri, options).then(data => {
const base64 = 'data:image/jpg;base64' + data;
resolve(base64); // are you sure you want to resolve the data and not the base64 string?
}).catch(err => {
console.log("​getFile -> err", err);
reject(err) ;
});

您可以在文档中查看有关不同选项的更多信息。 https://docs.expo.io/versions/latest/sdk/filesystem#expofilesystemreadasstringasyncfileuri-options

这是与 async/await 一起工作的小吃 https://snack.expo.io/Hk-m38wfN

关于react-native - 如何使用expo从文件系统读取jpg文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com