1 package pl.org.nowoczesnapolska.wlmobi;
4 @author Mauro Rocco http://www.toforge.com
6 Radek Czajka: don't prepend /sdcard/
9 import org.json.JSONArray;
10 import org.json.JSONException;
12 import android.util.Log;
14 import com.phonegap.DroidGap;
15 import com.phonegap.api.Plugin;
16 import com.phonegap.api.PluginResult;
19 import java.io.FileOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.HttpURLConnection;
25 public class Downloader extends Plugin{
28 public PluginResult execute(String action, JSONArray args, String callbackId) {
29 if (action.equals("downloadFile")) {
31 return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
32 } catch (JSONException e) {
33 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
37 return new PluginResult(PluginResult.Status.INVALID_ACTION);
42 PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
44 Log.d("DownloaderPlugin", "DIRECTORY CALLED "+dirName+" created");
45 File dir = new File(dirName);
47 Log.d("DownloaderPlugin", "directory "+dirName+" created");
51 File file = new File(dirName+fileName);
53 if(overwrite.equals("false") && file.exists()){
54 Log.d("DownloaderPlugin", "File already exist");
55 return new PluginResult(PluginResult.Status.OK, "exist");
58 URL url = new URL(fileUrl);
59 Log.d("DownloaderPlugin", "connecting to server for downloading " + url);
60 HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
61 ucon.setRequestMethod("GET");
62 ucon.setDoOutput(true);
65 Log.d("DownloaderPlugin", "download begining");
67 Log.d("DownloaderPlugin", "download url:" + url);
69 InputStream is = ucon.getInputStream();
71 byte[] buffer = new byte[1024];
75 FileOutputStream fos = new FileOutputStream(file);
77 while ( (len1 = is.read(buffer)) > 0 ) {
78 fos.write(buffer, 0, len1);
79 //new String(buffer, "ISO8859_1").getBytes("UTF-8"), 0, len1);
84 Log.d("DownloaderPlugin", "Download complete in" + fileName);
86 } catch (IOException e) {
88 Log.d("DownloaderPlugin", "Error: " + e);
89 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
93 return new PluginResult(PluginResult.Status.OK, fileName);