效果圖
//渲染的圖片,格式為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; }); }); }
有啥不懂的可以留言..