【问题标题】:How to check file exists or not in phonegap 2.9 with android?如何使用android在phonegap 2.9中检查文件是否存在?
【发布时间】:2013-12-06 11:07:15
【问题描述】:

我使用此代码从服务器下载歌曲:

JavaScript File

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://www.abcdefg.it/uploads/"+sound);
var filePath = "/sdcard/download/"+sound;

fileTransfer.download(
    uri,
    filePath,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {

        alert(JSON.stringify(error));

        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
    },
    false,
    {
        headers: {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);

Problem

如果 File Existsdcard 上设置条件,然后 不下载

如果 not Exist下载

Note

请注意,我使用的是 Phonegap 2.9.0

Request

如果您有任何想法/解决方案,请分享。 谢谢。

【问题讨论】:

    标签: android file cordova download


    【解决方案1】:

    使用这个插件:

    Java 插件:

    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.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    import org.apache.cordova.api.CallbackContext;
    import org.apache.cordova.api.CordovaPlugin;
    import org.apache.cordova.api.PluginResult;
    
    public class Downloader extends CordovaPlugin {
    
        public boolean execute(String action, JSONArray args,
                CallbackContext callbackContext) {
    
            if (!action.equals("downloadFile")) {
                callbackContext.sendPluginResult(new PluginResult(
                        PluginResult.Status.INVALID_ACTION));
                return true;
            }
            try {
    
                String fileUrl = args.getString(0);
                String fileName = args.getString(2);
                String dirName = args.getString(1);
                String overwrite = args.getString(3);
    
    
                callbackContext.sendPluginResult(this.downloadUrl(fileUrl, dirName,
                        fileName, overwrite, callbackContext));
                return true;
    
            } catch (JSONException e) {
    
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(
                        PluginResult.Status.JSON_EXCEPTION, e.getMessage()));
                return false;
    
            } catch (InterruptedException e) {
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(
                        PluginResult.Status.ERROR, e.getMessage()));
                return false;
            }
    
        }
    
        private PluginResult downloadUrl(String fileUrl, String dirName,
                String fileName, String overwrite, CallbackContext callbackContext)
                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.equals("false") && 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());
            }
        }
    }
    

    js 插件:

    cordova.define("cordova/plugin/downloader",
      function(require, exports, module) {
        var exec = require("cordova/exec");
        var Downloader = function () {};
    
    Downloader.prototype.downloadFile = function(fileUrl, dirName, fileName, overwrite, win, fail) {    
        if (overwrite == false)
            overwrite = "false";
        else
            overwrite = "true";
        exec(win, fail, "Downloader", "downloadFile", [ fileUrl, dirName, fileName, overwrite ]);
    
    };
    var downloader = new Downloader();
        module.exports = downloader;
    
    });
    if (!window.plugins) {
        window.plugins = {};
    }
    if (!window.plugins.downloader) {
        window.plugins.downloader = cordova.require("cordova/plugin/downloader");
    }
    

    像这样使用它:

    function downloadFile(fileUrl, dirName, fileName, overwrite) {
        window.plugins.downloader.downloadFile(
            fileUrl, 
            {overwrite : true}, 
            function(res) {
                alert(JSON.stringify(result));
            }, 
            function(error) {
                alert(error);
            }
        );
        window.plugins.downloader.downloadFile(fileUrl, dirName, fileName,overwrite);
        window.plugins.fileOpener.open("file://" + dirName + fileName);
    }
    

    【讨论】:

    • 在不同的帖子中问这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多