`
czpae86
  • 浏览: 713201 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

phonegap 实现文件下载

阅读更多

phonegap 文件下载

效果图:



 

 

 
 

package com.phonegap.plugins.downloader;

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

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Environment;
import android.util.Log;

public class Downloader extends Plugin {

	@Override
	public PluginResult execute(String action, JSONArray args, String callbackId) {

		if (!action.equals("downloadFile"))
			return new PluginResult(PluginResult.Status.INVALID_ACTION);

		try {

			String fileUrl = args.getString(0);
			JSONObject params = args.getJSONObject(1);

			String fileName = params.has("fileName") ? params
					.getString("fileName") : fileUrl.substring(fileUrl
					.lastIndexOf("/") + 1);

			String dirName = params.has("dirName") ? params
					.getString("dirName") : Environment
					.getExternalStorageDirectory().getPath() + "/download";

			Boolean overwrite = params.has("overwrite") ? params
					.getBoolean("overwrite") : false;

			return this.downloadUrl(fileUrl, dirName, fileName, overwrite,
					callbackId);

		} catch (JSONException e) {

			e.printStackTrace();
			return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
					e.getMessage());

		} catch (InterruptedException e) {
			e.printStackTrace();
			return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
		}

	}

	private PluginResult downloadUrl(String fileUrl, String dirName,
			String fileName, Boolean overwrite, String callbackId)
			throws InterruptedException, JSONException {

		try {

			Log.d("PhoneGapLog", "Downloading " + fileUrl + " into " + dirName
					+ "/" + fileName);

			File dir = new File(dirName);
			if (!dir.exists()) {
				Log.d("PhoneGapLog", "directory " + dirName + " created");
				dir.mkdirs();
			}

			File file = new File(dirName, fileName);

			if (!overwrite && file.exists()) {
				Log.d("DownloaderPlugin", "File already exist");

				JSONObject obj = new JSONObject();
				obj.put("status", 1);
				obj.put("total", 0);
				obj.put("file", fileName);
				obj.put("dir", dirName);
				obj.put("progress", 100);

				return new PluginResult(PluginResult.Status.OK, obj);
			}

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

			Log.d("PhoneGapLog", "Download start");

			InputStream is = ucon.getInputStream();
			byte[] buffer = new byte[1024];
			int readed = 0, progress = 0, totalReaded = 0, fileSize = ucon
					.getContentLength();

			FileOutputStream fos = new FileOutputStream(file);

			while ((readed = is.read(buffer)) > 0) {

				fos.write(buffer, 0, readed);
				totalReaded += readed;

				int newProgress = (int) (totalReaded * 100 / fileSize);
				if (newProgress != progress)
					progress = informProgress(fileSize, newProgress, dirName,
							fileName, callbackId);

			}

			fos.close();

			Log.d("PhoneGapLog", "Download finished");

			JSONObject obj = new JSONObject();
			obj.put("status", 1);
			obj.put("total", fileSize);
			obj.put("file", fileName);
			obj.put("dir", dirName);
			obj.put("progress", progress);

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

		} catch (FileNotFoundException e) {
			Log.d("PhoneGapLog", "File Not Found: " + e);
			return new PluginResult(PluginResult.Status.ERROR, 404);
		} catch (IOException e) {
			Log.d("PhoneGapLog", "Error: " + e);
			return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
		}

	}

	private int informProgress(int fileSize, int progress, String dirName,
			String fileName, String callbackId) throws InterruptedException,
			JSONException {

		JSONObject obj = new JSONObject();
		obj.put("status", 0);
		obj.put("total", fileSize);
		obj.put("file", fileName);
		obj.put("dir", dirName);
		obj.put("progress", progress);

		PluginResult res = new PluginResult(PluginResult.Status.OK, obj);
		res.setKeepCallback(true);
		success(res, callbackId);

		// Give a chance for the progress to be sent to javascript
		Thread.sleep(100);

		return progress;
	}

}

 

function Downloader() {
}

Downloader.prototype.downloadFile = function(fileUrl, params, win, fail) {

	// Make params hash optional.
	if (!fail)
		win = params;
	cordova.exec(win, fail, "Downloader", "downloadFile", [ fileUrl, params ]);
};

window.downloader =  new Downloader();

 

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/jquerymobile/themes/default/jquery.mobile-1.2.0.min.css" />
         <link rel="stylesheet" href="css/style.css" />
    
        <title>PhonegapTest</title>
    </head>
    <body>
        <div data-role="page">
        	<h3>phonegap 文件下载测试</h3>
        	<div style="padding:20%;">
        		<img src="#" id="img_001" style="width:150px;height:150px;border:1px solid #ccc;"/>        		
        	</div>
        	<div>progress:<span id="test_002"></span>%</div>
	        <a data-role="button" id="downloadBtn">download</a>
	    </div>
        <script type="text/javascript" src="js/cordova-2.2.0.js"></script>
        <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
        <script type="text/javascript" src="js/downloader.js"></script>
        <script type="text/javascript">
           $('#downloadBtn').bind('click',function(){
        	   $('#img_001').attr('src','#');
        	   window.downloader.downloadFile("http://7676.gmcc.net/images/newportal/bnt_tb01b.gif", {overwrite: true}, 
       			      function(res) {
       			        //alert(JSON.stringify(res));
       			        $('#test_002').text(res.progress);
       			        if(res.progress==100){
       			        	$('#img_001').attr('src',res.dir+'/'+res.file);
       			        }
       			        
       			    }, function(error) {
       			        alert(error);
       			    }
       			);
           });
        </script>
    </body>
</html>

 

  • 大小: 58.2 KB
  • 大小: 66.1 KB
  • 大小: 57.7 KB
分享到:
评论
5 楼 xu_miao 2014-06-17  
youtops 写道
为什么我的界面点击下载总是提示 Class not found
类找不到

 
我的也是   你解决了么?
4 楼 flyong86 2013-06-08  
我现在下载文件可以正常下载和监听进度,但是问题在于程序下载的同时用户去其它页面后程序在后台执行,但是不会再执行我的进度监听,完成监听的js回调方法

这是一件很痛苦的事情,通常我这里下载的文件比较大比如10M的zip,用户点了下载去其它页面,我在下载完成后会解压文件,但下载完成后就再也不会执行做解压的js(自己写的插件)

你是否也这样呢
3 楼 czpae86 2013-05-23  
_莎士比亚的梦 写道
请问一下你那个downloader.js是那里的js文件,那里可以得到


就是上面的js内容
2 楼 _莎士比亚的梦 2013-05-22  
请问一下你那个downloader.js是那里的js文件,那里可以得到
1 楼 youtops 2013-05-09  
为什么我的界面点击下载总是提示 Class not found
类找不到

相关推荐

Global site tag (gtag.js) - Google Analytics