简体   繁体   中英

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:

$scope.download = function() {
    Restangular.one(myAPI)
      .withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {

        //IE10 opens save/open dialog with filename.zip
        window.navigator.msSaveOrOpenBlob(response, 'filename.zip');

        //Chrome/FF downloads a file with random name                
        var url = (window.URL || window.webkitURL).createObjectURL(response);
        window.location.href = url;
    });
};

Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?

As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click

 var myBlob = new Blob(["example"],{type:'text/html'}) var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob); var anchor = document.createElement("a"); anchor.download = "myfile.txt"; anchor.href = blobURL; anchor.click(); 

Download attribute compatibility

只需使用https://www.npmjs.com/package/angular-file-saver浏览器支持表可以在这里看到: https//github.com/eligrey/FileSaver.js/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM