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 private 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 HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
60 ucon.setRequestMethod("GET");
61 ucon.setDoOutput(true);
64 Log.d("DownloaderPlugin", "download begining");
66 Log.d("DownloaderPlugin", "download url:" + url);
68 InputStream is = ucon.getInputStream();
70 byte[] buffer = new byte[1024];
74 FileOutputStream fos = new FileOutputStream(file);
76 while ( (len1 = is.read(buffer)) > 0 ) {
77 fos.write(buffer, 0, len1);
78 //new String(buffer, "ISO8859_1").getBytes("UTF-8"), 0, len1);
83 Log.d("DownloaderPlugin", "Download complete in" + fileName);
85 } catch (IOException e) {
87 Log.d("DownloaderPlugin", "Error: " + e);
88 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
92 return new PluginResult(PluginResult.Status.OK, fileName);