開發web app並且使用phonegap下載及打開附件

 在開發web app並且使用phonegap的情況下,附件下載着實是一件令人頭疼的事,什麼window.open或者window.location.href在webview中都不起作用,網上查了許久,沒有一篇完整講述“phonegap附件下載及打開附件”的例子,現在分享一下。

    首先,如果你可以接受的話,可以使用一種極其簡單的方式來完成,點擊操作之後,跳入手機默認瀏覽器進行下載,代碼如下
    navigator.app.loadUrl(encodeURI(url), { openExternal:true}); 
    注意,參數一定要加{ openExternal:true}參數,這個參數代表在另外的瀏覽器打開。 
    如果你不滿足於這種方式,可以使用以下方法: 
    phonegap附件下載,使用的方法是phonegap自帶的下載附件的方式,而打開附件用到的是phonegap插件,最終由安卓原生代碼來完成,不多說,代碼如下: 
    1. html文件(cordova.js是phonegap的庫文件) 
    <html> 
  <head> 
    <meta charset="UTF-8"> 
    <title>phonegap文件下載</title>  
    <script type="text/javascript" src="cordova.js"></script> 
    <script type="text/javascript"> 
    window.appRootDirName = "download_test"; 
    document.addEventListener("deviceready", onDeviceReady, false); 


    function onDeviceReady() { 
        console.log("device is ready"); 
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); 
    } 


    function fail() { 
        console.log("failed to get filesystem"); 
    } 


    function gotFS(fileSystem) { 
        console.log("filesystem got"); 
        window.fileSystem = fileSystem; 
        fileSystem.root.getDirectory(window.appRootDirName, { 
            create : true, 
            exclusive : false 
        }, dirReady, fail); 
    } 


    function dirReady(entry) { 
        window.appRootDir = entry; 
        console.log("application dir is ready"); 
    } 




    downloadFile = function(){ 
         
        alert("start"); 
        var fileTransfer = new FileTransfer(); 
        var uri = encodeURI("http://12.130.30.22:8080/uploadImagetest.xls"); 
        var filePath = window.appRootDir.fullPath + "/test.xls"; 
         
        alert(window.appRootDir.fullPath); 
        fileTransfer.download( 
            uri, 
            filePath, 
            function(entry) { 
                alert("success"); 
                alert(entry.fullPath); 
                //此處調用打開文件方法 
                OpenFile(entry.fullPath); 
                //window.location.href = window.appRootDir.fullPath; 
                console.log("download complete: " + entry.fullPath); 
            }, 
            function(error) { 
                alert("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); 
            } 
        );    
    } 
    function OpenFile(path){ 
        try { 
            alert('OpenFile'); 
            var array = []; 
            array[0] = path; 
            alert(array[0]); 
            cordova.exec(function(message) { 


            }, null, 'OpenFilePlugin', 'haha', array); 
        } catch(e) { 
            alert(e.message); 
        } 
    } 
</script> 
</head> 
<body> 
    <a href="#" οnclick="downloadFile()">Download File</a> 
</body> 
</html> 
2. 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.apache.cordova.api.CallbackContext; 
import org.apache.cordova.api.CordovaPlugin; 
import org.apache.cordova.api.PluginResult;   
import org.json.JSONArray;   
import org.json.JSONException;   
import org.json.JSONObject;   
   
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Environment;   
import android.util.Log;   
   
public class OpenFilePlugin extends CordovaPlugin {   
    @Override 
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {   
        try { 
            Context context = cordova.getActivity().getApplicationContext(); 
            //文件路徑 
            String path = args.getString(0).toLowerCase(); 
             
            int len = path.length(); 
            String lastThree = path.substring(len-3, len); 
            String lastFour = path.substring(len-4, len); 
            //判斷文件類型 
            //doc 
            if(lastThree.equals("doc") || lastFour.equals("docx")){ 
                Intent i = this.getWordFileIntent(path); 
                context.startActivity(i); 
            } 
            //excel 
            else if(lastThree.equals("xls") || lastFour.equals("xlsx")){ 
                Intent i = this. getExcelFileIntent(path); 
                context.startActivity(i); 
            } 
            //ppt 
            else if(lastThree.equals("ppt") || lastFour.equals("pptx")){ 
                Intent i = this. getPptFileIntent(path); 
                context.startActivity(i); 
            } 
            //pdf 
            else if(lastThree.equals("pdf")){ 
                Intent i = this.getPdfFileIntent(path); 
                context.startActivity(i); 
            } 
            //圖片 
            else if(lastThree.equals("jpg") || lastThree.equals("png")  
                    || lastThree.equals("gif") || lastThree.equals("bmp") 
                    || lastFour.equals("jpeg")){ 
                Intent i = this.getImageFileIntent(path); 
                context.startActivity(i); 
            } 
            //文本 
            else if(lastThree.equals("txt")){ 
                Intent i = this.getTextFileIntent(path, false); 
                context.startActivity(i); 
            } 
            //html 
            else if(lastThree.equals("htm") || lastFour.equals("html")){ 
                Intent i = this.getHtmlFileIntent(path); 
                context.startActivity(i); 
            } 
            //chm 
            else if(lastThree.equals("chm")){ 
                Intent i = this.getChmFileIntent(path); 
                context.startActivity(i); 
            } 
            //音頻 
            else if(lastThree.equals("mp3") || lastThree.equals("wav") 
                    || lastThree.equals("wma") || lastThree.equals("ogg") 
                    || lastThree.equals("ape") || lastThree.equals("acc")){ 
                Intent i = this.getAudioFileIntent(path); 
                context.startActivity(i); 
            } 
            //視頻 
            else if(lastThree.equals("avi") || lastThree.equals("mov") 
                    || lastThree.equals("asf") || lastThree.equals("wmv") 
                    || lastThree.equals("navi") || lastThree.equals("3gp") 
                    || lastThree.equals("ram") || lastThree.equals("mkv") 
                    || lastThree.equals("flv") || lastThree.equals("mp4") 
                    || lastFour.equals("rmvb") || lastThree.equals("mpg")){ 
                Intent i = this.getVideoFileIntent(path); 
                context.startActivity(i); 
            } 
            else{ 
                callbackContext.success("無法打開該文件!"); 
            } 
                 
            Intent i = getExcelFileIntent(path); 
            context.startActivity(i); 
        } catch (JSONException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
         
        return true; 
         
    }   
    //android獲取一個用於打開Excel文件的intent 
    public static Intent getExcelFileIntent(String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param)); 
     
        intent.setDataAndType(uri, "application/vnd.ms-excel"); 
     
        return intent; 
    } 
    //android獲取一個用於打開HTML文件的intent 


    public static Intent getHtmlFileIntent( String param ){ 


        Uri uri = Uri.parse(param ).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param ).build(); 
     
        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.setDataAndType(uri, "text/html"); 
     
        return intent; 


    } 


    //android獲取一個用於打開圖片文件的intent 


    public static Intent getImageFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "image/*"); 
     
        return intent; 


    } 


    //android獲取一個用於打開PDF文件的intent 


    public static Intent getPdfFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "application/pdf"); 
     
        return intent; 


    } 


    //android獲取一個用於打開文本文件的intent 


    public static Intent getTextFileIntent( String param, boolean paramBoolean){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        if (paramBoolean){ 
     
            Uri uri1 = Uri.parse(param ); 
         
            intent.setDataAndType(uri1, "text/plain"); 
     
        }else{ 
     
            Uri uri2 = Uri.fromFile(new File(param )); 
         
            intent.setDataAndType(uri2, "text/plain"); 
     
        } 
     
        return intent; 


    } 


    //android獲取一個用於打開音頻文件的intent 


    public static Intent getAudioFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     
        intent.putExtra("oneshot", 0); 
     
        intent.putExtra("configchange", 0); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "audio/*"); 
     
        return intent; 


    } 


    //android獲取一個用於打開視頻文件的intent 


    public static Intent getVideoFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     
        intent.putExtra("oneshot", 0); 
     
        intent.putExtra("configchange", 0); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "video/*"); 
     
        return intent; 


    } 


    //android獲取一個用於打開CHM文件的intent 


    public static Intent getChmFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "application/x-chm"); 
     
        return intent; 


    } 


    //android獲取一個用於打開Word文件的intent 


    public static Intent getWordFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "application/msword"); 
     
        return intent; 


    } 


    //android獲取一個用於打開PPT文件的intent 


    public static Intent getPptFileIntent( String param ){ 


        Intent intent = new Intent("android.intent.action.VIEW"); 
     
        intent.addCategory("android.intent.category.DEFAULT"); 
     
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     
        Uri uri = Uri.fromFile(new File(param )); 
     
        intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); 
     
        return intent; 


    } 
   
}   


3. config.xml 
<plugins> 
        <plugin name="OpenFilePlugin" value="yourPackage.OpenFilePlugin"/> 
</plugins> 


大功告成! 
發佈了1 篇原創文章 · 獲贊 15 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章