vue+tp5实现Element-ui自定义上传头像

1 篇文章 0 订阅

记录一次踩坑经历

vue代码,css部分参考官网就可以,可以自行修改

<el-upload
  class="avatar-uploader"
  action="upload"
  :headers="{'Content-Type':'multipart/form-data'}"
  :show-file-list="false"
  :auto-upload = "true"
  :http-request="uploadFile"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

//自定义上传图片
uploadFile(params){
	let file = params.file
	let imageType = file.type
	if(imageType != 'image/jpeg' && imageType != 'image/jpg' && imageType != 'image/png'){
		let isImage = false
	}else{
		let isImage = true
	}
	let isLt2M = file.size / 1024 / 1024 < 2
	if (!isImage) {
		this.open('上传头像图片只能是 JPG/PNG/JPEG 格式!')
		return
	}
	if (!isLt2M) {
		this.open('图片最大不能超过2M!')
		return
	}
	let formData = new FormData()
	formData.append('file',file)
	this.$axios({
		url:this.$store.state.baseUrl+'/api/user/uploadImg',
		method:'post',
		data:formData,
	    headers: {
	      'Content-Type':'multipart/form-data'
	    }
	}).then(response=>{
		if(response.data.code == 0){
			this.open(response.data.msg)
		}else{
			this.imageUrl = response.data.data.img
		}
	})
	
}

需要说明几个地方:
1.因为是自定义上传,所有在标签中必须添加属性http-request并绑定一个方法,例如:‘http-request’=“uploadFile”,属性action随意绑定一个字符串即可
2.需设置headers头,‘Content-Type’:‘multipart/form-data’,这里我在标签中和请求中均有设置
3.参数需要formData格式,即 let formData = new FormData()
formData.append(‘file’,file) 必不可少

php部分供参考,使用的是tp5框架,其它框架大同小异

/**
 * 上传头像
 */
public function uploadImg(Request $request)
{
    $file = $request->file('file');
    if($_SERVER['HTTP_HOST'] == 'localhost'){
        $url = Env::get('root_path').'static\upload\avatar';
    }else{
        $url = Env::get('root_path').'static/upload/avatar';
        $dirName = date('Ymd');
        if(!file_exists(Env::get('root_path').'static/upload/avatar/'.$dirName)){
            mkdir(Env::get('root_path').'static/upload/avatar/'.$dirName);
        }
    }
    $info = $file->move($url);
    if($info){
        $imgUrl = $_SERVER['HTTP_HOST'] == 'localhost' ? 'http://'.$_SERVER['HTTP_HOST'].'\/'.explode('/',$_SERVER['SCRIPT_NAME'])[1].'\static\upload\avatar\/'.$info->getSaveName() : $_SERVER['HTTP_HOST'].'/static/upload\avatar/'.$info->getSaveName();
        $this->success('上传成功',['img'=>$imgUrl]);
    }else{
        $this->error('上传失败,'.$file->getError());
    }
}

后端部分的几个说明:
1.linux服务器和本地在保存路径上的设置,服务器上用的是‘/’斜杠,而本地用的是‘\’斜杠,并且服务器上要设置写入的权限并判断目录是否存在,不存在则要先创建目录
2.保存成功以后,将图片的路径返回给前端即可,用于展示,当用户点击保存时,将路径存入数据库,即完成整个上传功能

张尊亮个人网站

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值