[英]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.