简体   繁体   English

Cordova:如何使用 vanilla JS 保存文本文件

[英]Cordova: How to save text files with vanilla JS

I am going to turn an array into a text file to send to a different device.我要将数组转换为文本文件以发送到不同的设备。 I have tried doing this using plugins and libraries, but that didn't seem to work for me.我曾尝试使用插件和库来做到这一点,但这似乎对我不起作用。 I was delighted to find this solution that does not use any plugins or libraries.我很高兴找到这个不使用任何插件或库的解决方案。 Sadly it works in my browser, but doesn't seem to work when trying it in the app itself.遗憾的是它在我的浏览器中工作,但在应用程序本身中尝试时似乎不起作用。

The code from the website:来自网站的代码:

const downloadToFile = (content, filename, contentType) => {
  const a = document.createElement('a');
  const file = new Blob([content], {type: contentType});
  
  a.href= URL.createObjectURL(file);
  a.download = filename;
  a.click();

    URL.revokeObjectURL(a.href);
};

document.querySelector('#btn2').addEventListener('click', () => {
  const textArea = 'This is the text that will be in the file'  
  downloadToFile(textArea, 'data.txt', 'text/plain');
});

Now I'm wondering is there a way to turn this into something that would work on android?现在我想知道有没有办法把它变成可以在 android 上运行的东西?

On Android with cordova, assuming you are using an array (my_array) as source for your file在带有cordova的Android上,假设您使用数组(my_array)作为文件的源

window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (dirEntry) {
        console.log('file system open: ' + dirEntry.name);
        var isAppend = false;
        createFile(dirEntry, nombreFichero, isAppend);
    }, onErrorLoadFs);

And then a function to create a file:然后是一个创建文件的函数:

function createFile(dirEntry, fileName, isAppend) {

var array_file = my_array.join("\n");
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {

    //writeFile(fileEntry, null, isAppend);
    writeFile(fileEntry, array_file, isAppend);

}, onErrorCreateFile);

And a function to write to file:还有一个写入文件的函数:

function writeFile(fileEntry, dataObj, isAppend) {
    fileEntry.createWriter(function (fileWriter) {

        fileWriter.onwriteend = function () {
            console.log("Successful file write..." + fileEntry.name);
        };

        fileWriter.onerror = function (e) {
            console.log("Failed file read: " + e.toString());
        };

        fileWriter.write(dataObj);
    });
}

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

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