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

Dee*_*ora 4 react-native expo

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

 FileSystem.downloadAsync(
                    httpUrl,
                    FileSystem.documentDirectory + location
                ).then((result)=>{
                    const uri = result.uri;
                }).catch((err)=>{
                    console.log("?getFile -> err", err);}
);
Run Code Online (Sandbox Code Playgroud)

文件成功保存在文件系统中。稍后当我尝试读取文件时,出现无法读取文件的错误。用于读取文件的代码:

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) ;
            });
 }
Run Code Online (Sandbox Code Playgroud)

上面的代码返回无法读取文件的错误。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",
:}
Run Code Online (Sandbox Code Playgroud)

读取文件时出错:

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.]
Run Code Online (Sandbox Code Playgroud)

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

And*_*rew 6

这是因为您没有告诉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) ;
        });
Run Code Online (Sandbox Code Playgroud)

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

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