1. 程式人生 > >webAppIOS如何實現多附件上傳功能

webAppIOS如何實現多附件上傳功能

webAppIOS如何實現多附件上傳功能

      app中經常需要實現上傳附件的功能,webApp在android中可以通過inputfile調取檔案。】

ios存在沙盒機制,無法通過inputfile 獲取檔案路徑。可以通過原生ios將第三方應用的檔案匯入到

douments或者downloads資料夾下面,通過mui的檔案訪問方式訪問。

 

實現效果:

 

實現程式碼:

<script type="text/javascript">
var dir="",root=[],current=null,parent=null,pitem=null,list=null;
var qqdir="file:///storage/emulated/0/tencent/QQfile_recv";
var iosqqdir="file:///var/mobile";
var htmlItem='<img class="ficon"></img><div><span class="fname"></span><br/><span class="finf">...</span></div>';

var iosqq="Document/MY/File";

var self,opener;

var primaryBack;



document.addEventListener( "plusready", function () {
	var path=plus.io.convertLocalFileSystemURL(iosqq);
//	alert(path.substring(0, path.lastIndexOf("/Documents"))+"/Documents");
	
	plus.io.requestFileSystem( path.substring(0, path.lastIndexOf("/Library")), function( fs ) {
//				alert(fs.root);
//				console
//alert(fs.root.fullPath);
		console.log(fs.root.fullPath);
		
//		console(JSON.stringify(fs.root));
		// 可通過fs操作PUBLIC_DOCUMENTS檔案系統 
		// ......
	}, function ( e ) {
//		alert( "Request file system failed: " + e.message );
	} );
	
	
	pitem = document.getElementById("pdir");
	list = document.getElementById("dcontent");

	// Get root item information
	var items = list.querySelectorAll(".fitemroot");
	for ( var i = 1; i < items.length; i++ ) {
		updateRootItem( items[i] );
	}
//	var item;
//	updateRootItem(item);
	
	
}, false );
// Update root information with item(HTMLUIElement)
function updateRootItem( item ) {
	var path=plus.io.convertLocalFileSystemURL("_documents");

	plus.io.resolveLocalFileSystemURL("file://"+path.substring(0, path.lastIndexOf("/Library"))+"/Library", function ( entry ) {

		var filename= entry.toLocalURL();
		filename=filename.substring(0,filename.length-1);
		var filename= filename.substring(filename.lastIndexOf("/") + 1).toLowerCase();
		document.querySelector("#fname").innerText = filename;
		

		root.push( entry );
		item.entry = entry;
		updateInf( item, entry );
	}, function ( e ) {
		outLine( "Update "+item.id+" information failed: "+e.message );
		alert( "Update "+item.id+" information failed: "+e.message);
	} );
}
// Update HTMLUIElement information with entry object
function updateInf( item, entry ) {
	entry.getMetadata( function ( metadata ) {
		var inf = item.querySelector(".finf");
		if ( entry.isDirectory ) {
			inf.innerText = "資料夾:"+metadata.directoryCount+"項,檔案:"+metadata.fileCount+"項";
		} else {
			inf.innerText = dateToStr(metadata.modificationTime);
		}
	}, function ( e ) {
		outLine( "Get metadata "+entry.name+" failed: "+e.message );
	}, false );
}
// Update ui with entries
function updateList( entries ) {
	var i,items = [].slice.apply(list.querySelectorAll(".fitem"));
	items.shift();
	// sort the entries
	entries.sort( sortCompareEntry )
	// Update item to ui
	for ( i = 0; i < entries.length; i++ ) {
		
		var di = null;
		if ( i < items.length ) {
			di=items[i];
			di.style.display = "block";
		} else {
			di = document.createElement("div");
			di.className = "fitem";
			di.setAttribute( "onclick", "openDir(this);" );
			di.innerHTML = htmlItem;
			list.appendChild( di );
		}
		
		di.entry = entries[i];
		di.id = di.entry.name;
		
//		if(di.id=="IFile"){
//			return;
//		}
		di.querySelector(".fname").innerText = di.id;
		di.querySelector(".finf").innerText = "";
		if ( entries === root ) {
			di.querySelector(".ficon").src = "../images/fdisk.png";
		} else {
			di.querySelector(".ficon").src = di.entry.isDirectory?"../images/fdir.png":"../images/ffile.png";
		}
		updateInf( di, di.entry );
	}
	// Hide other items
	for ( ; i < items.length; i++ ) {
		items[i].style.display = "none";
		items[i].entry = null;
	}
	// Reset scroll offset
	list.scrollTop = 0;
}
// Open directory with item(HTMLUIElement)
function openDir( item ) {
	var entry = item.entry;
	if ( !entry ) {
		outSet( "Open directory \""+item.id+"\" with null!" );
		return;
	}
	if ( entry.isDirectory ) {

		outSet( "Open directory: \""+dir+item.id+"\"" );
		var dirReader = entry.createReader();
		dirReader.readEntries( function( entries ) {
			parent = current;
			current = item.entry;
			dir = entry.toURL()+"/";
			// Dispaly up to parent item
			pitem.style.display = "block";
			// Update ui
			updateList( entries );
		}, function ( e ) {
			outLine( "Read directory "+item.id+" failed: "+e.message );
		} );
	} else {

				
		plus.io.resolveLocalFileSystemURL(dir+item.id, function ( entry ) {

				root.push( entry );
				item.entry = entry;
				updateInf( item, entry );
				
				
				localStorage.setItem("selectfile",entry.toLocalURL());
   						
   				$("#form").show();
				$("#filebackfile").hide();
				$("#filebackform").show();
				$("#dcontent").hide();
				
				
//				console.log(e.detail.fileurl);
		    var fileurl=entry.toLocalURL();

		    filename = fileurl.substring(fileurl.lastIndexOf("/") + 1).toLowerCase();
		    
		    var fileIndex = fileData.length;

			//附件名顯示
			htm = '';
			htm += '<a class="filebox" style="margin-left: 10px;display:inline-block;height: auto;word-break:break-all;">' + filename +
				'<img class="channelfile" data-fileIndex="' + fileIndex + '" src="../images/filedelete.png" style="display: inline-block;margin-left: 20px;width: 15px;height: 15px;" />' +
				'</a>';
			$("#filesList").append(htm);
	
			$(".channelfile").unbind();
			$(".channelfile").on("click", function() {
				//												alert($(this).attr("data-imgIndex"));
				$(this).parent('.filebox').remove();
	
				fileData.splice($(this).attr("data-fileIndex"), 1);
	
				//重置圖片下標
				$(".channelfile").each(function(index, item) {
					$(this).attr("data-fileIndex", index);
				});
	
			});
			
			
			plus.io.resolveLocalFileSystemURL(fileurl, function(entry){
								
									entry.file(function(file){
								
											var reader = new plus.io.FileReader();
											reader.onloadend = function (e) {
													console.log(e.target.result);
													// alert(e.target.result);
													var dataURL=e.target.result;
													
														dataURL = dataURL.split(",")[1];
//																		alert(dataURL);
														dataURL = window.atob(dataURL);
														var ia = new Uint8Array(dataURL.length);
														for(var i = 0; i < dataURL.length; i++) {
															ia[i] = dataURL.charCodeAt(i);
														};
//														var fileName="dfgdff.amr";
														var fileName = entry.toLocalURL().substring(entry.toLocalURL().lastIndexOf("/") + 1).toLowerCase();

														fileData.push(new Blob([ia], {
																type: fileName
														}, 0.8));
//														alert(fileData.length);
											};
											console.log(reader.readAsDataURL(file));
									},function(e){
											mui.toast("讀寫出現異常: " + e.message );
									})
							})
					
				
			}, function ( e ) {
				outLine( "Update "+item.id+" information failed: "+e.message );
				alert( "Update "+item.id+" information failed: "+e.message);
			});


	}
}
// Back to parent directory
function parentDir() {
	outSet( "Go to previous directory: \""+dir+"\"");
	var p = dir.lastIndexOf( "/", dir.length-2 );
	if ( p < 0 || !parent ) { // Up to root
		dir = "";
		current = parent = null;
		// hide up to parent item
		pitem.style.display = "none";
		// Update ui
		updateList( root );
	} else {
		var dirReader = parent.createReader();
		dirReader.readEntries( function( entries ) {
			dir = dir.substr( 0, p+1 );
			outLine( "Current directory: \""+dir+"\"" );
			current = parent;
			current.getParent( function ( entry ) {
				parent = entry;
			}, function ( e ) {
				outLine( "Get \""+current.name+"\" parent directory failed: "+e.message );
			} );
			parent = null;
			// Update ui
			updateList( entries );
		}, function ( e ) {
			outLine( "Read directory "+item.id+" failed: "+e.message );
		} );
	}
}
// Entry sort compare
function sortCompareEntry( a, b ) {
	if ( a.isDirectory && b.isFile ) {
		return -1;
	} else if ( a.isFile && b.isDirectory ) {
		return 1;
	} else {
		return a.name - b.name;
	}
}
// Format data to string
function dateToStr( datetime ) {
	var year = datetime.getFullYear(),
	month = datetime.getMonth()+1,
	date = datetime.getDate(),
	hour = datetime.getHours(),
	minutes = datetime.getMinutes(),
	second = datetime.getSeconds();
	if ( month < 10 ) {
		month = "0" + month;
	}
	if ( date < 10 ) {
		date = "0" + date;
	}
	if ( hour < 10 ) {
		hour = "0" + hour;
	}
	if ( minutes < 10 ) {
		minutes = "0" + minutes;
	}
	if ( second < 10 ) {
		second = "0" + second;
	}
	return (year+"-"+month+"-"+date+" "+hour+":"+minutes+":"+second);
}
		</script>
		<link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8"/>
		<style type="text/css">
.fitem {
	width: 96%;
	overflow: hidden;
	padding: 10px 2%;
	border-bottom: 1px solid #c6c6c6;
	text-align: left;
}
.fitem:active {
	background: #f4f4f4;
}
.ficon {
	height: 40px;
	float: left;
	margin-right: 8px;
}
.fup {
	line-height:40px;
}
.fname {
	font-weight: bolder;
	height: 22px;
	font-size: 16px;
}
.finf {
	width: 100px;
	height: auto;
	font-size: 12px;
}
		</style>