[英]Cordova: How to save text files with vanilla JS
我要将数组转换为文本文件以发送到不同的设备。 我曾尝试使用插件和库来做到这一点,但这似乎对我不起作用。 我很高兴找到这个不使用任何插件或库的解决方案。 遗憾的是它在我的浏览器中工作,但在应用程序本身中尝试时似乎不起作用。
来自网站的代码:
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');
});
现在我想知道有没有办法把它变成可以在 android 上运行的东西?
在带有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);
然后是一个创建文件的函数:
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);
还有一个写入文件的函数:
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.