Hendro Febrian
Hendro Febrian

Reputation: 222

Convert remote image to file base64 format

I have an image located remote (http://myimage.com/image.jpg). And I want to convert my image to base64 format.

Here's what I have done:

fileToBase64 = async (uri) => {
        console.log("processing file to base64");
        this.setState({ errorFoto: [false, 'lightgrey'] })
        const base64 = await FileSystem.readAsStringAsync(
            uri,
            {
                encoding: FileSystem.EncodingTypes.Base64,
            });
        let temp = this.state.fileBase64Upload;
        temp.push(base64);
        this.setState(
            {
                fileBase64Upload: temp,
                fileBase64: base64,
            }, () => { console.log('completedprocessing'); console.log('panjangnyafile64base', this.state.fileBase64Upload.length) }
        );
    }

But my code error:

Location 'http://myimage.com/image.jpg' isn't readable. - node_modules/react-native/Libraries/BatchedBridge/NativeModules.js:95:55 in - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:397:4 in __invokeCallback

Upvotes: 0

Views: 433

Answers (1)

Andrew
Andrew

Reputation: 28539

This is because the readAsStringAsync is for accessing a file that is stored on the device, you are trying to access a file that is not stored on the device. https://docs.expo.io/versions/latest/sdk/filesystem/#filesystemreadasstringasyncfileuri-options

You will have to download it using downloadAsync https://docs.expo.io/versions/latest/sdk/filesystem/#filesystemdownloadasyncuri-fileuri-options

Once you have downloaded the file you should be able to use readAsStringAsync to read the file from the device.

Upvotes: 1

Related Questions