随笔记录7 后端返回文件流,前端下载文件

var xhr = new XMLHttpRequest();
            xhr.open('GET', "/app/upload/getFile/"+id, true)
            xhr.responseType = 'arraybuffer';
            xhr.onload = function() {
                if (this.status === 200) {
                    var type = xhr.getResponseHeader('Content-Type')

                    var blob = new Blob([this.response], {type: type})
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        window.navigator.msSaveBlob(blob, fileName)
                    } else {
                        var URL = window.URL || window.webkitURL
                        var objectUrl = URL.createObjectURL(blob)
                        if (fileName) {
                            var a = document.createElement('a')
                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = objectUrl
                            } else {
                                a.href = objectUrl
                                a.download = fileName
                                document.body.appendChild(a)
                                a.click()
                                a.remove()
                            }
                        } else {
                            window.location = objectUrl
                        }
                    }
                }
            }
            xhr.send();

你可能感兴趣的:(随笔记录7 后端返回文件流,前端下载文件)