我正在尝试使用来自https://www.neontribe.co.uk/cordova-file-plugin-examples/
的示例使用cordova文件插件编写文件这是我的代码:
var errorHandler = function (fileName, e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'Storage quota exceeded';
break;
case FileError.NOT_FOUND_ERR:
msg = 'File not found';
break;
case FileError.SECURITY_ERR:
msg = 'Security error';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'Invalid modification';
break;
case FileError.INVALID_STATE_ERR:
msg = 'Invalid state';
break;
default:
msg = 'Unknown error';
break;
};
console.log('Error (' + fileName + '): ' + msg);
}
function writeToFile(fileName, data) {
data = JSON.stringify(data, null, '\t');
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (directoryEntry) {
directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// for real-world usage, you might consider passing a success callback
console.log('Write of file "' + fileName + '"" completed.');
};
fileWriter.onerror = function (e) {
// you could hook this up with our global error handler, or pass in an error callback
console.log('Write failed: ' + e.toString());
};
var blob = new Blob([data], { type: 'text/plain' });
fileWriter.write(blob);
}, errorHandler.bind(null, fileName));
}, errorHandler.bind(null, fileName));
}, errorHandler.bind(null, fileName));
}
writeToFile('example.json', { foo: 'bar' });
错误:
Error in Success callbackId: File681009815 : SyntaxError: Unexpected end of input:312
Uncaught SyntaxError: Unexpected end of input:314
Error in Success callbackId: File681009817 : TypeError: Illegal constructor:312
Uncaught TypeError: Illegal constructor:314
有关代码有什么问题的想法吗?
谢谢, 菲利普
答案 0 :(得分:1)
我猜你是在Android 4.x上测试的。我在Android 4.2.2上遇到了同样的问题。
首先,从platforms/android/platform_ww/cordova.js
第289,312-314行注释try {} catch {},以了解代码失败的确切行。它可能在var blob = new Blob([data], { type: 'text/plain' });
尝试在没有Blob()
的情况下直接将数据写入FileWriter:
var blob = new Blob([data], { type: 'text/plain' });
fileWriter.write(blob);
fileWriter.write(data);
本机api写一个String,所以只要你写文本它应该工作: https://github.com/apache/cordova-plugin-file/blob/master/src/android/FileUtils.java#L1129
另外,我会检查您尝试写入的数据是否正确,主要是由于此错误:
输入意外结束
最后,可能这个解决方案与此问题有关: https://stackoverflow.com/a/15302872/1786341