开发中遇到需要上传照片,并且返回URL给后端的一个小需求。用的是ElementUI组件。
代码部分
代码部分 fileInput(e){//上传图片 console.log(e); var files = e.file if(!files) return this.createImage(files, e); }, //利用lrz压缩图片 createImage (file, e) { let vm = this // lrz图片先压缩在加载、 this.lrz(file, { width: 480 }).then(function(rst) { // vm.postImage(rst.base64.slice(23),rst.base64Len);//上传至七牛云 vm.postImage(rst.file);//上传至七牛云 vm.imageUrl=rst.base64; return rst }).always(function() { // 清空文件上传控件的值 e.target.value = null }) }, postImage(file){ let vm = this; var formData = new FormData(); formData.append('file',file); this.$http({ url: this.$http.adornUrl('/sys/NiuYun/Token'), //七牛云提供的地址 method: 'get', params: this.$http.adornParams() }).then(({data}) => { if(data.errorCode=="0"){ this.qiniutoke = data.result.token; // var addr = res.data.result.url; formData.append('token',this.qiniutoke); let config = { headers:{'Content-Type':'multipart/form-data'} }; //设置请求头 this.axios.post('http://upload.qiniu.com/',formData, { headers:{'Content-Type':'image'} }).then((response) => { this.community.ComImg = response.data.key; }).catch(function(error) { console.log(error) }) }else{ return; this.$alert(data.errorMessage,'提示', { confirmButtonText: '确定', }); } }) },
elementUI提供的
handleAvatarSuccess(res, file) {//上传成功之后的方法 this.imageUrl = URL.createObjectURL(file.raw); }, 上传前限制图片的大小和类型 beforeAvatarUpload(file) {//上传之前的方法 const isJPG = file.type === 'image/jpeg'||'image/gif'||'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, },