Export Excel spreadsheet file stream way

There is a demand for project request interface for downloading the file stream excel and achieve download.

angular package post requests are always not print success callback in the result, go straight error.

He changed the idea of ​​using native ajax transmission request.

Download call downloadFile method, using native ajax, the focus here, to set responseType as 'blob',

Deposit when we pass the logon request needs to add Authorization token

downloadFile(fileName) {

        const that =this;

          const req =new XMLHttpRequest();

          req.open('POST', this.archiveNew +'/EC/query/downLoadOrder', true);

          req.responseType ='blob';

          req.setRequestHeader('Content-Type', 'application/json');

          req.setRequestHeader('Authorization', 'Bearer ' +this.jwtToken);


          req.onload =function() {

                    const data = req.response;

                    // Get the response by the conversion blob get blobUrl, dynamically create a call to a label click method to achieve download

                    const blob =new Blob([data]);

                    const blobUrl = window.URL.createObjectURL(blob);

                    that.downloadMethod(blobUrl, fileName);

             };

        // parameter must pay attention to the sequence of post pass JSON.stringify

          const data = JSON.stringify({'fileName': fileName});

          req.send(data);

}

downloadMethod(blobUrl, fileName) {

        // console.log(blobUrl);

          const a = document.createElement('a');

          a.className ='downloadFileA';

          a.style.display ='none';

          a.download = fileName;

          a.href = blobUrl;

          a.click();

          $('.downloadFileA').remove();

}

Reproduced in: https: //www.jianshu.com/p/917369dcd8bd

Guess you like

Origin blog.csdn.net/weixin_34391854/article/details/91142050