uniapp文件上传方案

167 阅读1分钟

利用input获得上传的file,首先创建input,type为file,input透明度为0,遮挡在上传按钮上方

html:

<view class="addBox" ref="input">

js:

mounted() {
	let input = document.createElement('input')
	input.style.width = "100%";
	input.type = 'file' //添加file类型
	// input.accept=".pdf" //限制只能上传PDF文件
	input.style.height = "100%";
	input.style.opacity = "0";
	input.style.overflow = "hidden"; //防止注意input 元素溢出
	input.id = 'file';
	let _this = this;
	this.$refs.input.$el.appendChild(input);
	input.onchange = (event) => {
		this.file = event.target.files[0];
		//上传方法
		console.log(this.file);
	}
},
methods: {
uploadAPI(path) {
	let _this = this
	let fData = new FormData();
	fData.append("file", path);
	let xhr = new XMLHttpRequest();
	xhr.open("POST", '地址', true);
	xhr.onload = function(e) {
		console.log("上传成功", JSON.parse(e.currentTarget.response)); //上传成功
	};
	xhr.onreadystatechange = () => {
		if (xhr.readyState == 4 && xhr.status == 200) { //上传成功
		let res = JSON.parse(xhr.responseText)
		if (res.code == 0 && res.data) {
			_this.sequence += 1
			_this.fileList.push({
			fileName: res.data.name,
			fileUrl: res.data.url,
			fileId: res.data.id,
			sequence: res.data.sequence
		    })
		_this.info.attachIds = res.data.id + ',' + _this.info.attachIds
		}
	    }
	}
	xhr.setRequestHeader('token', uni.getStorageSync('token')); //设置头部token
	xhr.send(fData)
},