我有一个Cordova应用程序,它需要读取我在Android和iOS上捆绑的各种数据文件。在构建应用程序时,我应该把它们放在哪个文件夹中?我应该如何读取它们?(它们都是几K到几十K左右的小文本文件)。
到目前为止,我已经在www/data/中使用了它们,并使用 AJAX 请求读取在基于本地浏览器的模拟器(带有Cordova Tools扩展的VSCode,并在Chrome中显示)上运行良好的文件,并将其作为Android上的部署应用程序。iOS失败,但出现错误"Cross origin requests are only supported for HTTP."
和"XMLHttpRequest cannot load file:///var/containers/Bundle/Application/[Some Hex code here]/MyApp.app/www/data/[data file name] due to access control checks."
然后我尝试了下面的代码,使用Cordova的文件插件:
function ReadAppBundleFile(fileName, successfn, errorfn = null)
{
var pathToFile = cordova.file.applicationDirectory + 'www/data/' + fileName;
console.log("pathToFile: ", pathToFile);
window.resolveLocalFileSystemURL(pathToFile, function(fileEntry) { // Get a local path to file
fileEntry.file(function(file) { // Get a file pointer to the file
var reader = new FileReader(); // Create a file reader
reader.onloadend = function(e) { // Function to run once readAsText (next line below) has finished loading the file
successfn(JSON.parse(this.result)); // Parse text file as JSON into JS object, then pass that to the supplied success function
};
reader.readAsText(file); // Read the file in as a text file
}, function(e) {console.log("file read error 1: ", e);}); // errorfn); // errorHandler.bind(null, fileName)); // If error in getting file pointer, call error function
}, function(e) {console.log("file read error 2: ", e);}); // errorfn); // errorHandler.bind(null, fileName)); // If error in getting local path to file, call error function
}
例如ReadAppBundleFile('somedatafile', function(data) { datafromfile = data; })
在模拟器上,此输出:
pathToFile: http://localhost:8000/www/data/somedatafile
和错误:DOMException: A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs.
那么,在构建应用程序时,我应该将数据放入哪个文件夹?我应该如何读取数据?
谢谢
1条答案
按热度按时间6qqygrtg1#
只需设置您的主机名和方案,
file://
将变为http://localhost