uni-app实现文件上传功能

uni-app实现文件上传功能

目前找到的比较好用的一款第三方插件
文件上传插件地址 https://ext.dcloud.net.cn/plugin?id=1015
插件下载选择下载示例项目zip ,可以直接运行项目查看效果

目录结构如下
uni-app实现文件上传功能_第1张图片

index.vue,是使用文件上传功能的当前页面

@up-success=“onSuccess” 是文件上传成功以后回传的数据




l-file.vue,是文件上传功能的封装组件,最后加载的是index.html文件

wv.overrideUrlLoading 监听返回的文件上传结果。

getRequest(url) {  
	let theRequest = new Object(); 
	let index = url.indexOf("?");
	if (index != -1) {  
		let str = url.substring(index+1);  
		let strs = str.split("&");  
		for(let i = 0; i < strs.length; i ++) {  
			theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
		} 
	}  
	return theRequest;  
},
appChooseFile({currentWebview,url,name = 'file',header,...formData} = {}) {
	// #ifdef APP-PLUS
	let wv = plus.webview.create("","/hybrid/html/index.html",{
		'uni-app': 'none', //不加载uni-app渲染层框架,避免样式冲突
		top: 0,
		height: '100%',
		background: 'transparent'
	},{
		url,
		header,
		key: name,
		...formData,
	});
	wv.loadURL("/hybrid/html/index.html")
	currentWebview.append(wv);
	wv.overrideUrlLoading({mode:'reject'},(e)=>{
		let {fileName,id} = this.getRequest(e.url);
		return this.onCommit(
		this.$emit('up-success',{fileName,data: {id,statusCode: 200}})
		);
	});
	// #endif
}

index.html 源码




	
		
		[文件管理器]
		
		
	

	
		
		
努力上传中..

h5-uploader.js 源码

负责h5代码上传文件及其进度展示,及上传结果回传

let mask = document.querySelector(".mask");
let fileDom = document.querySelector(".file");
let tis = document.querySelector(".tis");
let progress = document.querySelector(".tis-progress");
let cancel = document.querySelector(".cancel-btn");


let createUpload = (file, url, key='file', header = {},data = {}) => {
	console.log(`
	上传地址:${url}\n
	请求头:${JSON.stringify(header)}\n
	参数:${JSON.stringify(data)}
	`);
	if (!url) {return;}
	tis.style.display = 'flex';
	
	let formData = new FormData();
		formData.append(key, file);
	
	for (let keys in data) {
		formData.append(keys, data[keys]);
	}
	
	let xhr = new XMLHttpRequest();
	xhr.open("POST", url, true);
	
	for (let keys in header) {
		xhr.setRequestHeader(keys, header[keys]);
	}
	xhr.upload.addEventListener("progress", function(event) {
		if(event.lengthComputable){
			let percent = Math.ceil(event.loaded * 100 / event.total) + "%";
			progress.innerText = `努力上传中..${percent}`;
		}
	}, false);
	
	xhr.ontimeout = function(){
		// xhr请求超时事件处理
		progress.innerText = '请求超时';
		setTimeout(()=>{
			tis.style.display = 'none';
			plus.webview.currentWebview().close();
		},1000);
	};
	
	xhr.onreadystatechange = (ev) => {
		
		if(xhr.readyState == 4) {
			console.log('status:'+xhr.status);
			
			if (xhr.status == 200) {
				progress.innerText = '上传成功';
				console.log('返回数据:'+xhr.responseText);
				location.href = `callback?fileName=${file.name}&id=${xhr.responseText}`;
				
			}
			else {
				progress.innerText = '上传失败了';
			}
			
			setTimeout(()=>{
				tis.style.display = 'none';
				plus.webview.currentWebview().close();
			},1000);
			
		}
	};
	xhr.send(formData);
	
	cancel.addEventListener("click", ()=>{
		xhr.abort();
		plus.webview.currentWebview().close();
	});
}


mask.addEventListener("click", () => {
	plus.webview.currentWebview().close();
});

document.addEventListener('UniAppJSBridgeReady', () => {
	let {url,key,header,formData} = plus.webview.currentWebview();
	fileDom.addEventListener('change', (event) => {
		let file = fileDom.files[0];
		if(file.size > (1024*1024 * 10)) {
			plus.nativeUI.toast('单个文件不能超过10M,请重新上传');
			return;
		}
		console.log(file.name);
		createUpload(file, url, key,header,formData);
	}, false);
});

插件地址 https://ext.dcloud.net.cn/plugin?id=1015

你可能感兴趣的:(uni-app)