Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

javascript - JavaScript:创建并保存文件(JavaScript: Create and save file)

I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file.

(我有要写入文件的数据,然后打开文件对话框供用户选择保存文件的位置。)

It would be great if it worked in all browsers, but it has to work in Chrome.

(如果它在所有浏览器中都可以运行,那就太好了,但是必须在Chrome中运行。)

I want to do this all client-side.

(我想在所有客户端这样做。)

Basically I want to know what to put in this function:

(基本上我想知道要在此函数中添加什么:)

saveFile: function(data)
{
}

Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.

(该函数接收数据的位置,让用户选择一个位置来保存文件,并使用该数据在该位置创建一个文件。)

Using HTML is fine too, if that helps.

(如果有帮助,使用HTML也可以。)

  ask by user1756980 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):

(Awesomeness01 (无需锚标记)对代码进行了非常小的改进,并加上trueimage (支持IE)建议的添加:)

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

Tested to be working properly in Chrome, FireFox and IE10.

(经过测试可在Chrome,FireFox和IE10中正常工作。)

In Safari, the data gets opened in a new tab and one would have to manually save this file.

(在Safari中,数据会在新标签中打开,因此必须手动保存该文件。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...