How do you store a file locally using Apache Cordova 3.4.0

瘦欲@ 提交于 2019-12-02 18:37:10

Your file path contains a typo (or a grammar error):

var fileURL = "cdvfile://localhost/persistant/file.png";

You should write it as persistent.

Correct code:

var fileURL = "cdvfile://localhost/persistent/file.png";

Check out these links :

http://cordova.apache.org/docs/en/3.4.0/cordova_plugins_pluginapis.md.html#Plugin%20APIs https://github.com/apache/cordova-plugin-file/blob/dev/doc/index.md

http://cordova.apache.org/docs/en/3.0.0/cordova_file_file.md.html#File

First and second links provide you information about the plugin File and how to install it.

The third one show you how to use the File plugin.

Everytime you need to do something with Cordova, check if a plugin is available to do it :)

regards.

So far I have only tested this on Android, but I believe it should work as-is, or with little modification on IOS:

var url = 'example.com/foo'

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
    fileSystem.root.getFile('foo_file', {create: true, exclusive: false},
        function(file_entry){
            var ft = new FileTransfer()
            ft.download(url, file_entry.toURL(), function(fe){
                fe.file(function(f){
                    reader = new FileReader()
                    reader.onloadend = function(ev){
                        console.log('READ!', ev.target.result)
                    }
                    reader.readAsText(f)
                })
            })
        }
    )
})

Note that I also needed the contents of the file, so the bit at the end may be omitted if you don't need the contents at the time of downloading.

Also note that there is a far simpler method using window.saveAs but it's only available in Android 4.4.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!