小程序上传文件到服务器并回显可删除,包含图片视频文档等格式,附源码!
发布于 4 年前 作者 duqiang 2213 次浏览 来自 分享

我这里应用了vant-weapp插件,其实原理都是一样的,主要是调用微信的wx.uploadFile方法来实现;

//图片上传;html
<van-uploader max-count="1" 
	type="image" file-list="{{ fileList1 }}" use-before-read
	bind:before-read="beforeRead1" 
	bind:after-read="afterRead1" bind:delete="delete1" />
// 图片上传js

beforeRead1(event) {

	const {

		file,

		callback

	} = event.detail;

	callback(file.type === 'image');

},

delete1(event) {

	this.setData({

		fileList1: []

	})

},

afterRead1(event) {

	const {

		file

	} = event.detail;

	let that = this;

	let token = wx.getStorageSync('t') || "";

	wx.uploadFile({

		url: "http://127.0.0.0", // 这里写你们后台服务器的上传路径

		method: 'POST',

		header: {

			token:token,

			'content-type': "multipart/form-data; boundary=XXX"

		},

		filePath: file.url,

		name: 'file',

		formData: {

			bizType: 'SharedStores' //这里是额外的参数,后台不需要删除就行了

		},

		success(res) {

			let list = [{

				name: '图片',

				url: res.data

			}]

			that.setData({

				fileList1: list

			});

		},

	})

},

文件上传示例

//文件上传;html
<van-uploader max-count="1" accept="file" type="file" 
	file-list="{{ fileList3 }}" use-before-read
	deletable="{{ true }}" bind:before-read="beforeRead3" 
	bind:after-read="afterRead3" bind:delete="delete3">
	<view class="up-btn">+上传文件</view>
</van-uploader>
// 文件上传js

delete3(event) {

	this.setData({

		fileList3: []

	})

},

beforeRead3(event) {

	const {

		file,

		callback

	} = event.detail;

	callback(file.type === 'file');

},

afterRead3(event) {

	const {

		file

	} = event.detail;

	let that = this;

	let token = wx.getStorageSync('t') || "";

	wx.uploadFile({

		url: "http://127.0.0.0", // 这里写你们后台服务器的上传路径

		method: 'POST',

		header: {

			token:token,

			'content-type': "multipart/form-data; boundary=XXX"

		},

		filePath: file.url,

		name: 'file',

		formData: {

			bizType: 'SharedStores' //这里是额外的参数,后台不需要删除就行了

		},

		success(res) {

			let list = [{

				name: '文件',

				url: res.data

			}]

			that.setData({

				fileList3: list

			});

		},

	})

},
1 回复

不知道你有没有碰到这个问题,比如你在一个页面中有a,b,c三个van-uploader组件,当你点击其中一个组件上传文件或图片时,会触发另一个组件的after-read事件,然后会将该次上传文件返回的临时地址保存到那个组件的预览列表里面去

回到顶部