Today, we have implemented a file download function. I found some problems by searching for documents on the Internet.
First, add the following code to the control layer launch method:
1 // Wait for PhoneGap to load
2 document.addEventListener ("deviceready", onDeviceReady, false);
3 // PhoneGap is loaded
4 function onDeviceReady () {
5 // Find if there is a folder zgky, create it if there is none, and then find the absolute path of this folder
6 window.requestFileSystem (LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
7 //util.appRootDirName global variable, here is zgky
8 fileSystem.root.getDirectory (util.appRootDirName, {
9 create: true,
10 exclusive: false
11}, function (entry) {
12 // All the materials circulating on the Internet use fullPath. Here I get the relative directory. It will give an error when downloading, so I changed toURL ()
13 // This is a global global variable used to save the path
14 util.fullPath = entry.toURL ();
15 //console.log(‘Successfully created folder ’);
16 //console.log(util.fullPath);
17}, function () {
18 console.log ('Failed to create folder');
19});
20}, function () {
21 console.log ('Failed to create folder');
twenty two });
twenty three }
After obtaining an absolute path, we can use a method to download the object. The method is as follows. Call this method to download the object.
1 downFile: function (url) {
2 var me = this,
3 // Regular expression, used to get the file name
4 reg = / [^ \\\ /] * [\\\ /] + / g,
5 // Get, me.fullPath is obtained in the main control layer, this is a global variable
6 filePath = me.fullPath + "/" + url.replace (reg, ‘‘),
7 //
8 url = encodeURI (url),
9 fileTransfer = new FileTransfer ();
10 console.log (‘Downloading, please wait ...’);
11 fileTransfer.download (url, filePath,
12 function (entry) {
13 console.log (‘Successful download! Please check in‘ + entry.fullPath + ‘directory ');
15},
16 function (error) {
17 console.log (‘Download failed!’ + Error.source);
19});
20}
In Cordova, You need to introduce the following plug-ins when creating a project,
: Introduce file plug-ins
Cordova plugin add org. Apache. Cordova. File
: Introduce the file management plug-in
Cordova plugin add org. Apache. Cordova. File-Transfer