Phonegap android plugin for download files from url on sd card

[UPDATE]
You can found an updated version of my plugin on GitHub
Thanks to Phillip Neumann.
—————————————

Hi folks, today I want to share with you this very useful phonegap‘s plug-in.
As the title says this plug-in allow you to download a file (url) on the sd card in the folder of your choice.

Usage

downloader.downloadFile(fileUrl,dirName,fileName,overwrite,win,fail);

Params

fileUrl: <String> The url of the file to download
dirName: <String> The directory where you want to save the file
fileName: <String> The name of the file
overwrite: <Boolean> Overwrite the file if exist
win: <Function> Success callback function. Receive a parameter that contains the fileName if the file is wrote with success.  If the overwrite parameter is false and the file already exist the parameter will contain the string “exist”.
fail: <Function> Fail callback function. Receive a parameter that contains the error message

Source and installation

Like all phonegap android plugins is composed by tha java file and the javascript one.
For starting using this plugin first copy the java file into the java src folder of your android project, in my example  the package is called com.example.pgplugins.DownloaderPlugin.

File: Downloader.java

package com.example.pgplugins.downloaderPlugin;

/*
 @author Mauro Rocco http://www.maurorocco.com
*/

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

import com.phonegap.DroidGap;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Downloader extends Plugin{

 @Override
 public PluginResult execute(String action, JSONArray args, String callbackId) {
 if (action.equals("downloadFile")) {
 try {
 return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
 } catch (JSONException e) {
 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
 }
 }
 else {
 return new PluginResult(PluginResult.Status.INVALID_ACTION);
 }

 }

 private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
 try{
 Log.d("DownloaderPlugin", "DIRECTORY CALLED /sdcard/"+dirName+" created");
 File dir =     new File("/sdcard/"+dirName);
 if(!dir.exists()){
 Log.d("DownloaderPlugin", "directory /sdcard/"+dirName+" created");
 dir.mkdirs();
 }

 File file = new File("/sdcard/"+dirName+fileName);

 if(overwrite.equals("false") && file.exists()){
 Log.d("DownloaderPlugin", "File already exist");
 return new PluginResult(PluginResult.Status.OK, "exist");
 }

 URL url = new URL(fileUrl);
 HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
 ucon.setRequestMethod("GET");
 ucon.setDoOutput(true);
 ucon.connect();

 Log.d("DownloaderPlugin", "download begining");

 Log.d("DownloaderPlugin", "download url:" + url);

 InputStream is = ucon.getInputStream();

 byte[] buffer = new byte[1024];

 int len1 = 0;

 FileOutputStream fos = new FileOutputStream(file);

 while ( (len1 = is.read(buffer)) > 0 ) {
 fos.write(buffer,0, len1);
 }

 fos.close();

 Log.d("DownloaderPlugin", "Download complete in" + fileName);

 } catch (IOException e) {

 Log.d("DownloaderPlugin", "Error: " + e);
 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);

 }

 return new PluginResult(PluginResult.Status.OK, fileName);

 }

}

Now copy the following javascript file in the assets/www folder, remember to change the name of the package or the js will never found the java file.

File: downloader.js

function Downloader() {

}

Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {
 if(overwrite==false) overwrite="false";
 else overwrite="true";
 PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl,dirName,fileName,overwrite]);

};

PhoneGap.addConstructor(function() {
 PhoneGap.addPlugin("downloader", new Downloader());
 PluginManager.addService("Downloader","com.example.pgplugins.downloaderPlugin.Downloader");
});

For use it you have only to include the js file in the page and call it in this way

<script type="text/javascript" charset="utf-8" src="downloader.js"></script>
 <script type="text/javascript">

 window.plugins.downloader.downloadFile("http://www.maurorocco.com/archive.zip","sdcard/cache/","archive.zip", false,
 function(data){
 if(data=="exist"){
 alert("File already exist");
 }
 else{
 alert("File saved on sd card")
 }
 },function(data){ alert("error: "+data); });

 </script>

If you like it please jut say me “thanks” or send me 100000 € 😀 .
See you on the next post