user3616544
user3616544

Reputation: 1069

Display PDF from azure blob in browsers using Microsoft Azure Storage SDK for Node.js and JavaScript for Browsers

I am trying to use Microsoft Azure Storage SDK for Node.js and JavaScript for Browsers (https://github.com/Azure/azure-storage-node) to display PDF contents stored in Azure blob in browsers. So far I couldn't find any examples on how to do it.

I tried to follow the suggestion from https://github.com/Azure/azure-storage-node/issues/440, But couldn't make it work. I am using Azure function.

module.exports = async function (context, req) {

    let accessToken = await getAccessToken();

    let container = req.params.container;
    let filename = req.params.filename;
    let tokenCredential = new azure.TokenCredential(accessToken);
    let storageAccountName = process.env.StorageAccountName;
    let blobService = azure.createBlobServiceWithTokenCredential(`https://${storageAccountName}.blob.core.windows.net/`, tokenCredential);

    return new Promise((resolve, reject) => {
        let readStream = blobService.createReadStream(container, filename, function (error, result, response) {

                if (error) {
                    context.log(error);
                    context.log(response);
                    context.res = {
                        status: 400,
                        body: response
                    };
                    resolve(context.res);
                } 
        });

        let body = '';
        readStream.on('data', (chunk) => { 
            body += chunk;
        });

        readStream.on('end', () => { 
            context.res = {
                headers: {
                    'Content-Type': "application/pdf"
                },
                body: body
            };
            resolve(context.res);
        });
    });
};

But I got "Couldn't open PDF" error message in the browser or timeout error.

Upvotes: 2

Views: 1558

Answers (1)

FanJiachen
FanJiachen

Reputation: 106

For downloading blob in browser environment, using URL with SAS is recommended, and in the framework you are using, would an accessible URL pointing to PDF be enough?

Please follow example:

Download Blob BlobService provides interfaces for downloading a blob into browser memory. Because of browser's sandbox limitation, we cannot save the downloaded data trunks into disk until we get all the data trunks of a blob into browser memory. The browser's memory size is also limited especially for downloading huge blobs, so it's recommended to download a blob in browser with SAS Token authorized link directly.

Shared access signatures (SAS) are a secure way to provide granular access to blobs and containers without providing your storage account name or keys. Shared access signatures are often used to provide limited access to your data, such as allowing a mobile app to access blobs.

Upvotes: 1

Related Questions