问题描述
我将把一个数组变成一个文本文件,以发送到另一个设备。我尝试使用插件和库来执行此操作,但这似乎对我不起作用。我很高兴找到不使用任何插件或库的this解决方案。遗憾的是,它可以在我的浏览器中运行,但是在应用本身中尝试时似乎不起作用。
网站上的代码:
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);
});
}