1

In my webpage, I want to download file(ppt, pdf, xlsx) when I click <a/> tag. I used a tag with download attribute, but in IE it doesn't work.

So I referred to here (Download attribute on A tag not working in IE ), and now download works in IE but the file is not opened. I tried .xlsx file and when I open it, it says that

contents have problem.

How can I download and open my .xlsx .pdf .ppt file in IE with javascript?

I'm a beginner web programmer and I need some advice from a good developer like you. Thanks in advance.

this is my code

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <a id='a1' href="https://image.shutterstock.com/image-photo/colorful-flower-on-dark-tropical-260nw-721703848.jpg"
        download>excel</a>
    <script>
        function MS_bindDownload(el) {
            if (el === undefined) {
                throw Error('I need element parameter.');
            }
            if (el.href === '') {
                throw Error('The element has no href value.');
            }
            var filename = el.getAttribute('download');
            console.log("filename : " ,filename);
            if (filename === null){
                throw Error('I need download property.');
            }
            if (filename === '') {
                var tmp = el.href.split('/');
                filename = tmp[tmp.length - 1];
            }
            el.addEventListener('click', function (evt) {
                evt.preventDefault();
                var xhr = new XMLHttpRequest();
                xhr.onloadstart = function () {
                    xhr.responseType = 'blob';
                };
                xhr.onload = function () {
                    
                    navigator.msSaveBlob(xhr.response, filename);
                };
                xhr.open("GET", el.href, true);
                xhr.send();
            })
        }
        
        let element = document.querySelector('a');
        MS_bindDownload(element);
    </script>
</body>

</html>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jisu
  • 11
  • 2

0 Answers0