JavaScript blob filename without link

后端 未结 8 2172
一生所求
一生所求 2020-11-22 02:43

How do you set the name of a blob file in JavaScript when force downloading it through window.location?

function newFile(data) {
    var json = J         


        
8条回答
  •  忘掉有多难
    2020-11-22 03:03

    Late, but since I had the same problem I add my solution:

    function newFile(data, fileName) {
        var json = JSON.stringify(data);
        //IE11 support
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            let blob = new Blob([json], {type: "application/json"});
            window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {// other browsers
            let file = new File([json], fileName, {type: "application/json"});
            let exportUrl = URL.createObjectURL(file);
            window.location.assign(exportUrl);
            URL.revokeObjectURL(exportUrl);
        }
    }
    

提交回复
热议问题