简体   繁体   English

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

[英]Create a file using Javascript in Chrome on client side

I would like to know if I can create a text file and save the file in the users "Downloads" section in his/her computer using Javascript.我想知道我是否可以创建一个文本文件并使用 Javascript 将该文件保存在他/她计算机的用户“下载”部分中。 The way my feature should work is when the user clicks the submit button, I populate the users info in the text file and then save it in his machine.我的功能应该工作的方式是当用户单击提交按钮时,我在文本文件中填充用户信息,然后将其保存在他的机器中。 I would like this to work in Google Chrome.我希望它在谷歌浏览器中工作。

Is this possible?这可能吗? I have seen posts that specifically tell me that it is a serious security issue.我看过一些帖子,专门告诉我这是一个严重的安全问题。

Sure you can, using the brand new APIs.当然可以,使用全新的 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() {});

Enter this into the Chrome browser在 Chrome 浏览器中输入这个

data:text;charset=utf-8,helloWorld

So to construct the download for your users you would do something like因此,要为您的用户构建下载,您可以执行以下操作

data='<a href='data:text;charset=utf-8,'+uriEncode(yourUSERdataToDownload)+' >Your Download</a>

Then inject it into the dom for your user to press.然后将其注入 dom 供用户按下。

The following method works in IE11+, Firefox 25+ and Chrome 30+:以下方法适用于 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>

See this in Action: http://jsfiddle.net/Kg7eA/在行动中看到这个: http : //jsfiddle.net/Kg7eA/

Firefox and Chrome support data URI for navigation, which allows us to create files by navigating to a data URI, while IE doesn't support it for security purposes. Firefox 和 Chrome 支持用于导航的数据 URI,这允许我们通过导航到数据 URI 来创建文件,而 IE 出于安全目的不支持它。

On the other hand, IE has API for saving a blob, which can be used to create and download files.另一方面,IE 具有用于保存 blob 的 API,可用于创建和下载文件。

Try this:试试这个:

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

if you want to set the filename use download attribute of anchor tag:如果要设置文件名,请使用锚标记的download属性:

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

No, as that would allow you to create malicious programs in the client's computer, and harm his privacy.不,因为这会允许您在客户端的计算机中创建恶意程序,并损害他的隐私。

Also, requests to download files come from the server, so you'll need to create the file on the server, and serve it to the user, and hope he'll save it (if he requested for it it's likely that he will).此外,下载文件的请求来自服务器,因此您需要在服务器上创建文件,并将其提供给用户,并希望他能保存它(如果他提出请求,他很可能会这样做) .

Another possible solution to look at is to use data URIs or CSVs, but browser support for them is incomplete (IE), see Create a file in memory for user to download, not through server另一种可能的解决方案是使用数据 URI 或 CSV,但浏览器对它们的支持不完整(IE),请参阅在内存中创建文件供用户下载,而不是通过服务器

You will need server side functionality in order to server the user a text file (javascript is not enough).您将需要服务器端功能才能为用户提供文本文件(javascript 是不够的)。 You can create a server side script that creates the file and use javascript in order to prompt user to save it.您可以创建一个服务器端脚本来创建文件并使用 javascript 来提示用户保存它。

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

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 () {});
}

This link helped me a lot and solved my problem.此链接对我有很大帮助并解决了我的问题。 Cross browser solution:跨浏览器解决方案:

https://www.thewebflash.com/reading-and-creating-text-files-using-the-html5-file-api/ https://www.thewebflash.com/reading-and-creating-text-files-using-the-html5-file-api/

This is the most relevant part:这是最相关的部分:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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