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.api.Plugin;
15 import com.phonegap.api.PluginResult;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.HttpURLConnection;
24 public class Downloader extends Plugin{
27 public PluginResult execute(String action, JSONArray args, String callbackId) {
28 if (action.equals("downloadFile")) {
30 return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
31 } catch (JSONException e) {
32 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
36 return new PluginResult(PluginResult.Status.INVALID_ACTION);
41 PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
43 Log.d("DownloaderPlugin", "DIRECTORY CALLED "+dirName+" created");
44 File dir = new File(dirName);
46 Log.d("DownloaderPlugin", "directory "+dirName+" created");
50 File file = new File(dirName+fileName);
52 if(overwrite.equals("false") && file.exists()){
53 Log.d("DownloaderPlugin", "File already exist");
54 return new PluginResult(PluginResult.Status.OK, "exist");
57 URL url = new URL(fileUrl);
58 Log.d("DownloaderPlugin", "connecting to server for downloading " + url);
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);