phonegap下载文件并打开
来源:互联网 发布:python 连接sqlserver 编辑:程序博客网 时间:2024/06/06 03:19
这里分为两部分:1、用phonegap下载文件到移动设备;2、下载到移动设备的文件在WEB端通过Phonegap打开。
首先,对于第一部分,可以通过已有的FileTransfer来实现,也可以自己写插件实现文件下载,这里我采用现成的,毕竟官方的代码写的相对比较完善;第二部分则需要自己实现打开文件的插件了,因为没有提供现成可用的。
OK!Let's Start!
html中引用的javascript代码如下:
window.appRootDirName = "download"; //定义文件下载后的存放目录 document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() {console.log("device is ready");window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;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");}//下载文件function download(path,fileName){ var fileTransfer = new FileTransfer();var uri = encodeURI(path);var fileURL = "/mnt/sdcard/download/"+fileName;fileTransfer.onprogress = showUploadingProgress;navigator.notification.progressStart("", "当前下载进度");fileTransfer.download( uri, fileURL, function(entry) { console.log("download complete: " + entry.fullPath); navigator.notification.progressStop(); alert("下载成功,文件位置:"+ entry.fullPath);if (!confirm("是否打开文件?")) { window.event.returnValue = false; }else{ OpenFile(entry.fullPath);} }, function(error) { console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("upload error code" + error.code);navigator.notification.progressStop(); alert("下载文件错误!"); }, false, { headers: { "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" } });} // 显示上传进度function showUploadingProgress(progressEvt) {if (progressEvt.lengthComputable) {navigator.notification.progressValue(Math.round((progressEvt.loaded / progressEvt.total) * 100));}}//打开文件 function OpenFile(path){ // alert('OpenFile'); var openFilePlugin=cordova.require('com.gzx.open.OpenFile');openFilePlugin.openFile("/mnt/sdcard"+path, {}, function (result) { alert(result); }, function (error) { alert("打开文件错误!"); }); }
下面是,需要引入的打开文件的js,openFile.js
cordova.define('com.gzx.hello.OpenFile', function(require, exports, module){var exec = require("cordova/exec");/** * Constructor. * */function OpenFilePllugin() { };OpenFilePllugin.prototype.openFile = function (fileUrl, params,successCallback, errorCallback) {alert("gafdfa"); if (errorCallback == null) { errorCallback = function (){ }; } if (typeof errorCallback != "function") { console.log("OpenFilePllugin failure: failure parameter not a function"); return;}if (typeof successCallback != "function"){ console.log("OpenFilePllugin failure: success callback parameter must be a function"); return;}if (!errorCallback) successCallback = params;exec(successCallback, errorCallback, 'OpenFile', 'openFile',[fileUrl, params]); };var openFilePllugin = new OpenFilePllugin();module.exports = openFilePllugin; });对应的实现类OpenFile.java,如下:
package com.gzx.hello;import java.io.File;import org.apache.cordova.CallbackContext;import org.apache.cordova.CordovaPlugin;import org.json.JSONArray;import org.json.JSONException;import android.content.Context;import android.content.Intent;import android.net.Uri;public class OpenFile extends CordovaPlugin {/* * (non-Javadoc) * * @see org.apache.cordova.CordovaPlugin#execute(java.lang.String, * org.json.JSONArray, org.apache.cordova.CallbackContext) */@Overridepublic boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {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);// 判断文件类型// docif (lastThree.equals("doc") || lastFour.equals("docx")) {Intent i = this.getWordFileIntent(path);context.startActivity(i);}// excelelse if (lastThree.equals("xls") || lastFour.equals("xlsx")) {Intent i = this.getExcelFileIntent(path);context.startActivity(i);}// pptelse if (lastThree.equals("ppt") || lastFour.equals("pptx")) {Intent i = this.getPptFileIntent(path);context.startActivity(i);}// pdfelse 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, true);context.startActivity(i);}// htmlelse if (lastThree.equals("htm") || lastFour.equals("html")) {Intent i = this.getHtmlFileIntent(path);context.startActivity(i);}// chmelse 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 blocke.printStackTrace();}return true;}// android获取一个用于打开Excel文件的intentpublic 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文件的intentpublic 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获取一个用于打开图片文件的intentpublic 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文件的intentpublic 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获取一个用于打开文本文件的intentpublic 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获取一个用于打开音频文件的intentpublic 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获取一个用于打开视频文件的intentpublic 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文件的intentpublic 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文件的intentpublic 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文件的intentpublic 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;}}
对于,配置文件等操作,请参照之前的博文。
0 0
- phonegap下载文件并打开
- 下载文件并打开
- android下载文件并打开
- Wex5 文件下载并打开
- PhoneGap文件下载
- React Native 下载并打开pdf文件
- Android下载并打开PDF文件
- 使用h5+API下载并打开文件
- mui 下载文件并打开word文档
- Android 下载文件并调用相关插件打开
- JSP/Web环境下载Excel文件并打开,不在IE中直接打开的方法
- PhoneGap创建Android项目并使用eclipse打开
- 开发web app并且使用phonegap下载及打开附件
- 创建并打开文件
- 直接打开下载文件
- android 自带downloadManager下载apk文件,并打开安装包
- Android 实现应用下载并在通知栏展示进度通知 打开APK文件
- java打开并显示文件
- CentOS 修改系统字符集编码
- JavaScript Date(日期)对象
- Linux---TCP连接数
- Doxygen 一个程序的文件产生工具,可将程序中的特定批注转换成为说明文件
- Axis WSDD文件参考文档
- phonegap下载文件并打开
- Vim命令合集
- setter方法的内部实现【不要在init和dealloc函数中使用accessor】
- PCB布高速线时需要考虑得信号传输延时
- 查找指定目录下的文件夹或文件
- Mina源码分析——IoService
- day64(5.15)MyEclipse 10.0及更高版本激活
- it民工的华丽亦或是失败的转型(一)
- 长度最多为6个汉字或12个字母数字JS