How to display a file in new browser tab using a download link

If you have a link to a file that can be used to download any file stored in cloud storage, you can use the same to render the file in a new browser tab in JavaScript.

Following is a sample script to do the same:

getFilePreview(fileURL, fileType) {
            console.log("Inside getFilePreview()");
            try {
                let renderDoc = "<html><head></head><body>"
                if (fileType === 'image/png' || fileType === 'image/jpg' || fileType === 'image/jpeg') {
                    renderDoc += "<div style='width: 600px; height: 600px;'><img src='" + fileURL + "' alt='Image from Dropbox'style='width: 100%; height: 100%; object-fit: contain;'></div>";
                } else if (fileType === 'application/pdf') {
                    renderDoc += "<embed src='" + fileURL + "' type='application/pdf' width='600px' height='600px'>";
                } else {
                    renderDoc += "<h3>File preview not available<h3>";
                }
                renderDoc += "</body></html>";
                var blob = new Blob([renderDoc], { type: 'text/html' });
                var url = URL.createObjectURL(blob);
                window.open(url, '_blank');
            } catch (error) {
                console.log("Error in getFilePreview", error);
            }
        }

Leave a comment

Your email address will not be published. Required fields are marked *