问题描述:
无论使用 Ionic 封装的 import { File } from '@ionic-native/file';
,还是直接使用 Cordova 插件 cordova-plugin-file
, 写文件都是正常的,但是读文件就不会触发函数调用之后的操作,无论是使用以下何种方法:
- IN IONIC NATIVE:
readAsText(path, file).then().catch();
readAsDataURL(path, file).then().catch();
readAsBinaryString(path, file).then().catch();
readAsArrayBuffer(path, file).then().catch();
- IN CORDOVA:
document.addEventListener('deviceready', () => { window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory, root => { alert(JSON.stringify(root)); root.getFile('demo.txt', { create: true }, fileEntry => { alert(JSON.stringify(fileEntry)); fileEntry.file(function (file) { var reader = new FileReader(); reader.onloadend = function () { console.log("Successful file read: " + this.result); displayFileData(fileEntry.fullPath + ": " + this.result); }; reader.readAsText(file); // OR reader.readAsDataURL(file); // OR reader.readAsBinaryString(file); // OR reader.readAsArrayBuffer(file); }, onErrorReadFile); }, error => { alert(JSON.stringify(error)) }); }, error => { alert(JSON.stringify(error)) }); });
在 IONIC 并不能 resolve
或 reject
,在 CORDOVA 中不能触发后续函数。
解决方案:
参照以下资料:
- https://github.com/ionic-team/ionic2-app-base/issues/126
- https://github.com/ionic-team/ionic-native/issues/505
- https://github.com/ionic-team/ionic-native/issues/2117
原因看起来是 zone.js 冲突,因为我菜嘛,就不细细去看了,具体解决的做法就是在 index.html
中把 <script src="build/polyfills.js"></script>
这行代码放到最前面就可以了。
总结
我在 Google 中是这么搜的:nothing happened ionic file readAsDataURL
,再次不得不感叹 Google 的强大。