从网址到SD卡的phonegap下载文件

时间:2011-08-31 07:50:45

标签: android cordova

I  am working on phonegap with android. i want to download a file from given url to my sd card.


**this is my index.html**


<!DOCTYPE HTML>
<html>
  <head>
    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>PhoneGap Demo With JQuery Mobile</title>
      <link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" />
      <link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" />
      <script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script>
      <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
      <script src="jquery.mobile/jquery.mobile-1.0b2.js"></script>
      <script type="text/javascript" charset="utf-8" src="main.js"></script>

    <script type="text/javascript" charset="utf-8" src="downloader.js"></script>
 <script type="text/javascript">
 function down1()
 {

   window.plugins.downloader.downloadFile("http://192.168.1.214/sample/Winter.jpg","/mnt/sdcard/","archive.zip", false,
   function(data){
   if(data=="exist")
   {
     alert("File already exist");
   }
 else
 {
   alert("File saved on sd card")
 }
 },function(data){ alert("error is : "+data); });
 }
 </script>
    </head>
  <body>
  <div data-role="button" onclick="down1();">Get data</div>

  </body>
</html>



**this is my 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() {
    console.log('=============i am in addConstructor================');
 PhoneGap.addPlugin("downloader", new Downloader());
 PluginManager.addService("Downloader","com.example.pgplugins.DownloaderPlugin");
});


**this is my Downloader.java**

package com.example.pgplugins.DownloaderPlugin;
//package com.example.pgplugins.downloaderPlugin;
/*
 @author Mauro Rocco http://www.toforge.com
*/

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

import android.util.Log;

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

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

public class Downloader extends Plugin{

 @Override
 public PluginResult execute(String action, JSONArray args, String callbackId) {
    System.out.println("=============i am in head class================");
 if (action.equals("downloadFile")) {
 try {
 return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
 } catch (JSONException e) {
 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
 }
 }
 else {
 return new PluginResult(PluginResult.Status.INVALID_ACTION);
 }

 }

 private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
 try{
 Log.d("DownloaderPlugin", "DIRECTORY CALLED /sdcard/"+dirName+" created");
 File dir =     new File("/sdcard/"+dirName);
 if(!dir.exists()){
 Log.d("DownloaderPlugin", "directory /sdcard/"+dirName+" created");
 dir.mkdirs();
 }

 File file = new File("/sdcard/"+dirName+fileName);

 if(overwrite.equals("false") && file.exists()){
 Log.d("DownloaderPlugin", "File already exist");
 return new PluginResult(PluginResult.Status.OK, "exist");
 }

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

 Log.d("DownloaderPlugin", "download begining");

 Log.d("DownloaderPlugin", "download url:" + url);

 InputStream is = ucon.getInputStream();

 byte[] buffer = new byte[1024];

 int len1 = 0;

 FileOutputStream fos = new FileOutputStream(file);

 while ( (len1 = is.read(buffer)) > 0 ) {
 fos.write(buffer,0, len1);
 }

 fos.close();

 Log.d("DownloaderPlugin", "Download complete in" + fileName);

 } catch (IOException e) {

 Log.d("DownloaderPlugin", "Error: " + e);
 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);

 }

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

 }

}

**and this is my simple main class:-**

package com.example.pgplugins.DownloaderPlugin;

import com.phonegap.*;
import android.os.Bundle;

public class musicdownloader extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}


when i run this program, it is not doing anything. This is my whole project code, so please tell me what is mistake i have done.

2 个答案:

答案 0 :(得分:2)

您是否按照此页面中的说明操作:https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader我已经毫无问题地使用了这个插件。

另外,我注意到URL是内部IP,手机或模拟器是否可以访问它?

要安装插件,请将downloader.js移动到项目的www文件夹中,并在html文件中包含对它的引用。 在项目的src /文件夹中创建一个名为“com / phonegap / plugins / downloader”的文件夹。 并将java文件复制到该新文件夹中。 将以下内容添加到res / xml / plugins.xml文件

答案 1 :(得分:1)

PhoneGap 1.3.0中有一个来自URL的下载方法