Download Blob as file in Javascript

While we are working with Javascript we may find our self in a situation where we need to let users download blob as File.

So In this post, I’ll share basic javascript function which allows us to download blob as a file in the browser.


const downloadBlobAsFile = function(data, filename){
				const contentType = 'application/octet-stream';
        if(!data) {
            console.error(' No data')
            return;
        }

        if(!filename) filename = 'filetodonwload.txt'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: contentType}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  [contentType, a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
    
    // call the function 
    const data = "some data";
    const fileName = "filetodonwload.txt";
    downloadBlobAsFile(data, fileName);

You can find a working sample here. 

🙂

Advertisements

I am a passionate software developer. I develop software using microsoft technologies and other trending web technologies. currently works at sitecore as a developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s