效果图
//渲染的图片,格式为glob
<vue-cropper
ref="cropper"
:img="options.img"
:info="true"
:autoCrop="options.autoCrop"
:autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight"
:fixedBox="options.fixedBox"
@realTime="realTime"
/>
//图片上传组件
<el-upload action="#" :http-request="requestUpload" :show-file-list="false" name="file" :before-upload="beforeUpload" :headers="headers"> <el-button size="small"> 选择 <i class="el-icon-upload el-icon--right"></i> </el-button> </el-upload>
// 上传预处理 beforeUpload(file) { if (file.type.indexOf("image/") == -1) { this.msgError("文件格式错误,请上传图片类型,如:JPG,PNG后缀的文件。"); } else {
//选择图片转换成可以渲染格式 const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { this.options.img = reader.result; }; console.log("file", file); this.fileUpload = file }, // 上传图片 uploadImg() { let that = this this.$refs.cropper.getCropBlob(data => { let formData = new FormData(); // formData.append("avatarfile", data); // console.log("data", data); // console.log("data.type", data.type); // console.log("this.fileUpload", this.fileUpload); // let file=this.blobToFile(data,data.type) //判断文件名是否存在(存在是新增,不存在则为修改) // if (typeof(this.fileUpload.name) == ‘undefined‘) { // console.log(‘this.optionsImg‘, this.optionsImg) // } else { // console.log(‘this.fileUpload.name‘, this.fileUpload.name) // } //判断的依据,是否是更新,更新是没有文件名的,更新要把缓存的数据转成file类型,目前是glob;
//转换成file类型,可以根据后端接收类型自行转换成glob或者file格式 let file = new File([data], typeof(this.fileUpload.name) == ‘undefined‘ ? this.optionsImg : this.fileUpload.name, { type: data.type,lastModified: Date.now()}); file.uid = Date.now(); formData.append("file", file); console.log("file", file); //调用更新的方法(调用接口) uploadAvatar(formData).then(response => {
if(response.code==200){ this.open = false; //转成base64(也可以封装成一把方法进行调用) var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function() { that.options.img = reader.result; // console.log(reader.result); //获取到base64格式图片 store.commit(‘SET_AVATAR‘, that.options.img);
} }; // } that.msgSuccess("修改成功"); that.visible = false; }); }); }
有啥不懂的可以留言..