在客户端的Chrome中使用Javascript创建文件

在客户端的Chrome中使用Javascript创建文件,javascript,google-chrome,google-chrome-extension,facebook-javascript-sdk,dom-events,Javascript,Google Chrome,Google Chrome Extension,Facebook Javascript Sdk,Dom Events,我想知道我是否可以创建一个文本文件,并使用Javascript将该文件保存在他/她的计算机的用户“下载”部分。我的功能的工作方式是,当用户单击submit按钮时,我在文本文件中填充用户信息,然后将其保存在他的机器中。我想这在谷歌浏览器工作 这可能吗?我看到一些帖子专门告诉我这是一个严重的安全问题。不,因为这会让你在客户端的计算机上创建恶意程序,并损害他的隐私 此外,下载文件的请求来自服务器,因此您需要在服务器上创建文件,并将其提供给用户,并希望用户将其保存(如果他请求,很可能他会保存) 另一种可

我想知道我是否可以创建一个文本文件,并使用Javascript将该文件保存在他/她的计算机的用户“下载”部分。我的功能的工作方式是,当用户单击submit按钮时,我在文本文件中填充用户信息,然后将其保存在他的机器中。我想这在谷歌浏览器工作


这可能吗?我看到一些帖子专门告诉我这是一个严重的安全问题。

不,因为这会让你在客户端的计算机上创建恶意程序,并损害他的隐私

此外,下载文件的请求来自服务器,因此您需要在服务器上创建文件,并将其提供给用户,并希望用户将其保存(如果他请求,很可能他会保存)


另一种可能的解决方案是使用数据URI或CSV,但对它们的浏览器支持不完整(即,请参阅),您需要服务器端功能才能为用户提供文本文件(javascript不够)。
您可以创建创建文件的服务器端脚本,并使用javascript提示用户保存该文件

在“用户提交”按钮上,您可以在服务器上创建文件,并将用户重定向到文件的url,从该url自动下载文件。

当然可以,使用全新的API

 window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

 window.requestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {
    fs.root.getFile('test.bin', {create: true}, function(fileEntry) { // test.bin is filename
        fileEntry.createWriter(function(fileWriter) {
            var arr = new Uint8Array(3); // data length

            arr[0] = 97; // byte data; these are codes for 'abc'
            arr[1] = 98;
            arr[2] = 99;

            var blob = new Blob([arr]);

            fileWriter.addEventListener("writeend", function() {
                // navigate to file, will download
                location.href = fileEntry.toURL();
            }, false);

            fileWriter.write(blob);
        }, function() {});
    }, function() {});
}, function() {});

将其输入Chrome浏览器

data:text;charset=utf-8,helloWorld
因此,要为用户构建下载,您可以执行以下操作

data=”

然后将其插入dom中供用户按下。

尝试以下操作:

document.body.innerHTML+="<a id='test' href='data:text;charset=utf-8,"+encodeURIComponent("hi")+"'>Your Download</a>";
document.getElementById('test').click();

以下方法适用于IE11+、Firefox 25+和Chrome 30+:

<a id="export" class="myButton" download="" href="#">export</a>
<script>
    function createDownloadLink(anchorSelector, str, fileName){
        if(window.navigator.msSaveOrOpenBlob) {
            var fileData = [str];
            blobObject = new Blob(fileData);
            $(anchorSelector).click(function(){
                window.navigator.msSaveOrOpenBlob(blobObject, fileName);
            });
        } else {
            var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
            $(anchorSelector).attr("download", fileName);               
            $(anchorSelector).attr("href", url);
        }
    }

    $(function () {
        var str = "hi,file";
        createDownloadLink("#export",str,"file.txt");
    });

</script>

函数createDownloadLink(主播选择器、str、文件名){
if(window.navigator.msSaveOrOpenBlob){
var fileData=[str];
blobObject=新的Blob(fileData);
$(主播选择器)。单击(函数(){
window.navigator.msSaveOrOpenBlob(blobobObject,文件名);
});
}否则{
var url=“data:text/plain;charset=utf-8,”+encodeURIComponent(str);
$(主播选择者).attr(“下载”,文件名);
$(主播选择者).attr(“href”,url);
}
}
$(函数(){
var str=“你好,文件”;
createDownloadLink(“导出”,str,“file.txt”);
});
请看这一行动:

Firefox和Chrome支持用于导航的数据URI,这允许我们通过导航到数据URI来创建文件,而IE不支持用于安全目的的数据URI


另一方面,IE有保存blob的API,可以用来创建和下载文件。

这个链接帮助了我很多,解决了我的问题。跨浏览器解决方案:

var isIE = /*@cc_on!@*/ false || !! document.documentMode; // At least IE6
var uri = "some data"; //data in file
var fileName = "file.i4cvf"; // any file name with any extension
if (isIE) {
    var fileData = ['\ufeff' + uri];
    var blobObject = new Blob(fileData);
    window.navigator.msSaveOrOpenBlob(blobObject, fileName);
} else //chrome
{
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
        fs.root.getFile(fileName, {
            create: true
        }, function (fileEntry) {
            fileEntry.createWriter(function (fileWriter) {
                var fileData = ['\ufeff' + uri];
                var blob = new Blob(fileData);
                fileWriter.addEventListener("writeend", function () {
                    var fileUrl = fileEntry.toURL();
                    var link = document.createElement('a');
                    link.href = fileUrl;
                    link.download = fileName;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }, false);
                fileWriter.write(blob);
            }, function () {});
        }, function () {});
    }, function () {});
}

这是最相关的部分:

if ('msSaveOrOpenBlob' in navigator) {

    navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
    var downloadLink = document.createElement('a');
    downloadLink.download = fileName;
    downloadLink.innerHTML = 'Download File';
    if ('webkitURL' in window) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}


我确实看过了。但我不明白如何根据用户输入来填充文件。他甚至特别询问了Chrome。自动下载?说谁?我的意思是在服务器端,在服务器上保存文件并将用户重定向到指向该文件的url(www.domain.com/abc.txt)后,它会自动提示用户在客户端保存文件…当我尝试执行此代码时,我被定向到本地链接。里面没有内容。我想要一个文本文件,所以我更改了名称并按照@Praveen上的说明操作:我遗漏了一些东西。请查看我的更新代码。新的小提琴工作正常吗?导航到一个文件似乎不会下载它。您的示例运行良好,但我的示例导航到一个链接而没有下载。@Praveen:那么不确定;对我来说,它开始下载
test.bin
。你用的是什么分机?也许这很重要。@pimvdb链接断开了哈,这就是我找到它时的想法=)您如何设置下载文件的文件名?我得到一个名为“download”的无扩展文件,有没有办法改变它?@Flater:使用
download
属性。它可以在Chrome上工作,允许你下载任何文件名的内容,不再传递毫无意义的消息,也不再试图使用各种API,结果却发现它们不受欢迎。谢谢欢迎光临,请查看
window.location=“mailto:someone@example.com?Subject=Hello%20再次“
还有!太神奇了。。。但是如何设置文件名呢?我得到了“下载”作为文件名,并没有扩展名。@YanKingYin使用
Download=“filename”
作为标记的属性。这在chrome中似乎不再有效。要解决这个问题,请看哪个可行。在哪里可以找到关于这个问题的解释?请添加一个更详细的解释-欢迎链接到解决方案,但请确保您的答案在没有它的情况下是有用的:这样您的其他用户就会知道它是什么以及为什么存在,然后引用你链接到的页面最相关的部分,以防目标页面不可用。
if ('msSaveOrOpenBlob' in navigator) {

    navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
    var downloadLink = document.createElement('a');
    downloadLink.download = fileName;
    downloadLink.innerHTML = 'Download File';
    if ('webkitURL' in window) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}