出处:http://my.oschina.net/u/1011854/blog/169434 再次 谢谢作者!

在开发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="#" onclick="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>

大功告成!

phonegap 附件下载及打开附件的更多相关文章

  1. javamail模拟邮箱功能获取邮件内容-中级实战篇【内容|附件下载方法】(javamail API电子邮件实例)

    引言: JavaMail jar包下载地址:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...

  2. IE8下导入EXCEL数据传到客户端以附件下载

    IE8下导入EXCEL数据传到客户端以附件下载方式出现,而不显示数据,解决方法:以text/html格式返回. HttpResponseMessage message = new HttpRespon ...

  3. 解析:使用easyui的form提交表单,在IE下出现类似附件下载时提示是否保存的现象

    之前开发时遇到的一个问题,使用easyui的form提交表单,在Chrome下时没问题的,但是在IE下出现类似附件下载时提示是否保存的现象. 这里记录一下如何解决的.其实这个现象不光是easyui的f ...

  4. android 后台附件下载

    在service中通过在oncreat()中开启一个线程,轮训ArrayList<AttachmentTask> 我这个附件下载的任务list ,ArrayList<Attachme ...

  5. FTP服务器中文环境引起润日下载不了附件问题解析

    20160229日某农商行因为FTP下载功能有问题,导致当天所有涉及FTP文件下载的交易都不能正常使用,对于银行来说影响还是比较大.现将当天出问题的原因及处理过程解析如下,忘能给碰到类似问题的同行以供 ...

  6. Python 实现 Discuz论坛附件下载权限绕过漏洞

    背景:最近压力有些大,想玩点游戏放松下,去Mac论坛下载,发现需要各种权限,于是蛋疼了. 所以,上网查了discuz! x3.1破解,手动替换,发现出现“链接已过期”.所以写了下面程序. 0.将下列代 ...

  7. xml或其他附件下载到客户端

    //xml Document document=DocumentHelper.createDocument(); Element root=document.addElement("root ...

  8. 使用easyui的form提交表单,在IE下出现类似附件下载时提示是否保存的现象

    之前开发时遇到的一个问题,使用easyui的form提交表单,在Chrome下时没问题的,但是在IE下出现类似附件下载时提示是否保存的现象. 这里记录一下如何解决的.其实这个现象不光是easyui的f ...

  9. javaweb-JSP action中附件下载的写法

     附件下载(包括图片,exl,word)在前台必须给出一个iframe 或者类似于window的窗口,另外,Java文件下载不能通过ajax进行请求,必须添加src属性首选,前台的链接拼接html如下 ...

随机推荐

  1. python 中的json解析库

    当一个json 数据很大的时候.load起来是很耗时的.python中常见的json解析库有cjson,simplesjson,json, 初步比较了一下, 对于loads来讲 simplejson ...

  2. Linux Mint下安装JDK

    Linux Mint 17下安装的是默认的OpenJDK,可以使用java -version查看 现在需要使用Sun/Oracle官方的JDK:http://www.oracle.com/techne ...

  3. jqGrid详解及高级应用(十四)

    一:jqGrid 是一个用来显示网格数据的jQuery插件,文档比较全面,附带中文版本.  二:官方主页http://www.jqgrid.com/目前最新版本:jqGrid 3.7 Beta在线文档 ...

  4. SQL调用系统存储过程整理

    SQL系统存储过程用法整理: xp_cmdshell --*执行DOS各种命令,结果以文本行返回. xp_fixeddrives --*查询各磁盘/分区可用空间 xp_loginconfig --*报 ...

  5. AngularJS基本指令

    <!doctype html> <html  ng-app> <head>   <meta charset="UTF-8">   & ...

  6. java作业5

    (一)用你的大数类实现加和减两个功能(乘除阶乘未实现) import java.util.Scanner; import java.io.IOException; import java.io.Inp ...

  7. Qt Charts示例

    Qt 5.7 有一些变化,把原来商业版的几个模块用GPLv3协议放到了社区版本里: Qt Charts (GPLv3) Qt Data Visualization (GPLv3) Qt Virtual ...

  8. 怎么在手机浏览器上访问电脑本地的文件,局域网内,自建WiFi也可以

    首先,电脑要有Mysql+Apache+PHP环境,我直接用Wampsever,开启环境后手机和电脑要再同一个局域网内,然后电脑上打开win+R,输入cmd,再输入ipconfig,就可以看着这台的电 ...

  9. SecureCRT最佳配色方法+直接修改默认配置方法 - imsoft.cnblogs

    SecureCRT默认显示效果是黑白且刺眼的主题,看起来很不舒服.经过一番搜索,总结结果如下,直接设置默认属性,设置一次,不需再改. 效果图: 具体操作方法: Options->Global O ...

  10. LCS (nlogn)

    最长上升子序列的O(n*logn)算法分析如下: 先回顾经典的O(n^2)的动态规划算法,设a[t]表示序列中的第t个数,dp[t]表示从1到t这一段中以t结尾的最长上升子序列的长度,初始时设dp [ ...