Vue:文件上傳(原生)

UI框架不滿足使用場景。需要點擊頭像上傳頭像!

H5部分

 

<van-cell-group>
    <input type="file" id="updateAvatar" style="display: none" multiple @change="handleFile"/>
		<div style="display: flex; height: 50px;  margin-top: 10px;" @click="selectAvatar">
			<div style="display: flex; width: 50%; height: 50px;">
				<span style="margin-left: 16px; font-size: 15px; display: flex; line-height: 50px; text-align: left;">{{$t('userInfos.Avatar')}}</span>
			</div>
		    <div style="height: 50px; width: 50%;">
			<img style="margin-left: 40%; width: 50px;  height: 50px; border-radius: 50%;" :src="AvatarUrl" >
			<van-icon style="float: right; margin-right: 16px;  line-height: 50px;" name="arrow" /></img>
		    </div>
		</div>	
	<van-cell style="text-align: left;" :title="this.$t('userInfos.NickName')" :value="nickName" is-link to="updateNickname" />
	<van-cell style="text-align: left;" :title="this.$t('userInfos.Birthday')" :value="birthday" @click="openShow"/>
</van-cell-group>

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配置訪問代理服務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章