Vue:文件上传(原生)

UI框架不满足使用场景。需要点击头像上传头像!

Vue:文件上传(原生)_第1张图片

H5部分

 


    
		
{{$t('userInfos.Avatar')}}

JS部分

export default {
		name: 'userInfos',
		data() {
			return {
				nickName:JSON.parse(localStorage.getItem("userInfo")).nickName,
				birthday: JSON.parse(localStorage.getItem("userInfo")).birthday,
				AvatarUrl:JSON.parse(localStorage.getItem("userInfo")).Avatar,
			}
		},
		mounted() {
			
		},
		methods: {
			selectAvatar(){
				var data = document.getElementById("updateAvatar").click();
			},
			handleFile(e){
				console.log(e)
				console.log(e.target.files[0])
				const isJpgOrPng = e.target.files[0].type==="image/jpeg"||e.target.files[0].type==="image/png"
				if(isJpgOrPng){
					Toast('上传图片类型错误!仅支持PNG,JPG图片');
					if(e.target.files[0].size < 2*1024*1024){
						var file1 = e.target.files[0]
						var formData = new FormData();
						formData.append('file',file1)
						console.log(formData)//http://192.168.10.100:3000/System/v1/api
						Toast.loading({
						  mask: true,
						  message: '图片上传中!',
						  duration: 50000
						});
						this.$Request_post(this.$ImgUrl+"/upClientUserAvatar?email="+new Date().getTime(), formData).then(res=>{
							console.log(res)
							var data = {
								AvatarUrl:res.data.fileurl
							}
							this.$Request_post(this.$request+"/updateAvatar",data).then(res=>{
								console.log(res)
								var userinfo = JSON.parse(localStorage.getItem("userInfo"))
								userinfo.Avatar = data.AvatarUrl
								localStorage.setItem("userInfo",JSON.stringify(userinfo))
								this.AvatarUrl = data.AvatarUrl
								console.log("1")
								Toast.clear();
								this.$router.go(0)
							})
						})
					}else{
						Toast('图片大小超过2M!');
					}
				}else{
					Toast('上传文件类型错误!');
				}
			}
		},

后台文件上传部分参考:Node.js(Koa2)图片上传--Nginx配置访问代理服务

你可能感兴趣的:(Vue)