PhoneGap文件下载

Downloader:

package com.phonegap.Sample;

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

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

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

public class Downloader extends Plugin
{

	@Override
	public PluginResult execute(String arg0, JSONArray arg1, String arg2)
	{
		if(arg0.equals("downloadFile"))
		{
			try
			{
				return this.downloadUrl(arg1.getString(0),arg1.getString(1),arg1.getString(2),arg1.getString(3));
				
			}
			catch (JSONException e)
			{
				e.printStackTrace();
				return new PluginResult(PluginResult.Status.ERROR,"param errors");
			}
		}else
		{
			return new PluginResult(PluginResult.Status.INVALID_ACTION);
		}
		
	}
	
	private PluginResult downloadUrl(String fileUrl, String dirName, String fileName,String overWirte)
	{
		File dir = new File(dirName);
		if(!dir.exists())
		{
			dir.mkdirs();
		}
		
		File file = new File("mnt/sdcard/" + dirName,fileName);
		if(overWirte.equals("false") && file.exists())
		{
			return new PluginResult(PluginResult.Status.OK,"exist");
		}
		
		try
		{
			URL url = new URL(fileUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			FileOutputStream fos = new FileOutputStream(file);
			while((len = is.read(buffer))!=-1)
			{
				fos.write(buffer,0,len);
			}
			fos.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return new PluginResult(PluginResult.Status.ERROR,"error : " + e);
		}
		return new PluginResult(PluginResult.Status.OK,fileName);
	}
	
	
}

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.phonegap.Sample.Downloader");
});

html:





无标题文档









	下载




你可能感兴趣的:(PhoneGap文件下载)