0

I want to connect to azure blob storage via my React-Native Application. I am getting this error: [Error: Account connection string is only supported in Node.js environment] Does this mean that I cannot connect to Azure using connection string in react-native application? Please provide alternatives to do so.

    import { BlobServiceClient} from "@azure/storage-blob";

    const downloadfirmwareFile=async()=>{
        try{
            const blobServiceClient=BlobServiceClient.fromConnectionString(azureConnectionString)
            const containerClient=blobServiceClient.getContainerClient(azureContainerName)
            const blobClient=containerClient.getBlobClient({filepath}) //exact location where the file is stored
            const downloadedBlobResponse= await blobClient.download(0)
            const downloadedBlob= await downloadedBlobResponse.blobBody
            if(!downloadedBlob){
                console.log("Blob data is undefined")
                return;
            }
            else{
                const arrayBuffer= await downloadedBlob.arrayBuffer()
                const binaryData= Buffer.from(arrayBuffer).toString()
                const filePath=`${RNFS.DocumentDirectoryPath}/downloaded-file.bin`
                await RNFS.writeFile(filePath,binaryData,'binary')
                console.log("file created")
            }
        }
        catch(error){
            console.log(error)
        }
    }

I expected this code in react-native to connect with azure blob storage and download the file from there but unfortunately does not do that.

3
  • Hope this helps: stackoverflow.com/questions/61314287/… Commented Jun 12, 2024 at 12:08
  • @Nouphal.M should this code which uses crypto be used in the Client-Side apps like react-native apps? Commented Jun 12, 2024 at 12:26
  • @FreyalShah Can you try with the SAS token once? Commented Jun 13, 2024 at 10:11

1 Answer 1

0

I got the same error with the Azure Storage connection string in my environment.

ERROR  Error downloading blob: [Error: Account connection string is only supported in Node.js environment]
ERROR  Download error: [Error: Account connection string is only supported in Node.js environment]

enter image description here

@Nouphal.M Thanks for the comment.

As mentioned in this SO thread, BlobServiceClient.fromConnectionString won't work in Node.js runtime. So, I used the Azure storage Blob SAS URL in the React-Native code to download a blob from a container.

Here is the complete code with the Blob SAS URL.

Code :

src/App.js :

import React from 'react';
import { SafeAreaView, Text, StyleSheet } from 'react-native';
import DownloadButton from './components/DownloadButton';
const App = () => {
    const sasUrl = '<blobSASURL>';
    return (
        <SafeAreaView style={styles.container}>
            <Text style={styles.title}>Azure Blob Storage Example</Text>
            <DownloadButton sasUrl={sasUrl} />
        </SafeAreaView>
    );
};
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
    },
});
export default App;

src/services/AzureBlobService.js :

import RNFetchBlob from 'rn-fetch-blob';
const downloadFileFromBlobStorage = async (sasUrl) => {
    try {
        const response = await RNFetchBlob.config({
            fileCache: true,
            appendExt: 'bin',
        }).fetch('GET', sasUrl);
        const statusCode = response.info().status;
        if (statusCode !== 200) {
            throw new Error(`Failed to download blob: ${statusCode}`);
        }
        const filePath = response.path(); 
        console.log('File downloaded successfully:', filePath);
        return filePath;    } catch (error) {
        console.error('Error downloading blob:', error);
        throw error; 
    }
};
export { downloadFileFromBlobStorage };

src/components/DownloadButton.js :

import React from 'react';
import { TouchableOpacity, Text, Alert, StyleSheet } from 'react-native';
import { downloadFileFromBlobStorage } from '../services/AzureBlobService';
const DownloadButton = ({ sasUrl }) => {
    const handleDownload = async () => {
        try {
            const filePath = await downloadFileFromBlobStorage(sasUrl);
            Alert.alert('File Downloaded', `File saved at: ${filePath}`);
        } catch (error) {
            Alert.alert('Error', 'Failed to download file. Please try again later.');
            console.error('Download error:', error);
        }
    };
    return (
        <TouchableOpacity style={styles.button} onPress={handleDownload}>
            <Text style={styles.buttonText}>Download File</Text>
        </TouchableOpacity>
    );
};
const styles = StyleSheet.create({
    button: {
        backgroundColor: '#1E90FF',
        padding: 10,
        borderRadius: 5,
        marginTop: 20,
    },
    buttonText: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: 16,
        textAlign: 'center',
    },
});
export default DownloadButton;

Output :

I ran the above React-Native code with the below command.

npx react-native run-android

enter image description here

I got the below page in my emulator and clicked on Download File button as below,

enter image description here

The blob downloaded successfully as below,

enter image description here

Logs :

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.