AngularJS - File Download through AJAX

后端 未结 2 768
遥遥无期
遥遥无期 2021-01-13 15:42

I created an angular js program for downloading a file from the server here follows the code

HTML Code



        
2条回答
  •  [愿得一人]
    2021-01-13 16:11

    I created a more angular way solution. The server has to provide content-type and content-disposition if you want to sync with server info, although you could add type and download properties manually.

     vm.export = function () {
                //PopUps.showLoading()
                $http.get(Url).then(function (result) {
                    //PopUps.hideLoading()
                    var headers = result.headers()
                    var blob = new Blob([result.data], { type: headers['content-type'] })
                    var windowUrl = (window.URL || window.webkitURL)
                    var downloadUrl = windowUrl.createObjectURL(blob)
                    var anchor = document.createElement("a")
                    anchor.href = downloadUrl
                    var fileNamePattern = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
                    anchor.download = fileNamePattern.exec(headers['content-disposition'])[1]
                    document.body.appendChild(anchor)
                    anchor.click()
                    windowUrl.revokeObjectURL(blob)
                })
            }
    

提交回复
热议问题