效果图
引入图片处理插件
npm install vue-cropper
前端
<template>
<!-- 添加编辑窗口 -->
<drag-modal :visible="visible" :showBtn="false" :title="this.$t('title')" :width="650" :bodyStyle="'height:453px;overflow:auto;padding:3px;'" @cancel="close">
<a-spin :tip="this.$t('dataProcessing')" :spinning="loading">
<a-row>
<a-col :span="12" :style="{height: '350px'}">
<vue-cropper ref="cropper" :img="options.img" :info="true" :autoCrop="options.autoCrop" :autoCropWidth="options.autoCropWidth" :autoCropHeight="options.autoCropHeight" :fixedBox="options.fixedBox" @realTime="realTime">
</vue-cropper>
</a-col>
<a-col :span="12" :style="{height: '350px'}">
<div class="avatar-upload-preview">
<img :src="previews.url" :style="previews.img" />
</div>
</a-col>
</a-row>
<br />
<a-row>
<a-col :span="12">
<a-upload name="file" accept=".png,.jpg,.jpeg" :beforeUpload="beforeUpload" :showUploadList="false">
<a-button icon="upload">{{ $t('choice') }}</a-button>
</a-upload>
<a-button icon="plus" @click="changeScale(1)" />
<a-button icon="minus" @click="changeScale(-1)" />
<a-button icon="undo" @click="rotateLeft" />
<a-button icon="redo" @click="rotateRight" />
</a-col>
<a-col :span="12" style="text-align:center;">
<a-button :disabled="!haveFile" type="primary" @click="save()">{{ $t('save') }}</a-button>
</a-col>
</a-row>
</a-spin>
</drag-modal>
</template>
<script>
//弹窗可拖动插件
import dragModal from "@/components/dialog/dragModal";
//图片处理插件
import { VueCropper } from 'vue-cropper'
import { uploadAvatar } from "@/api/system/sys_user";
import { setLoginUser } from "@/utils/util";
export default {
name: "avatar-dialog",
i18n: require("./i18n"),
components: { dragModal, VueCropper },
data() {
return {
loading: false,
visible: false,
haveFile: false,
options: {
img: '',
autoCrop: true,
autoCropWidth: 200,
autoCropHeight: 200,
fixedBox: true
},
previews: {}
};
},
props: {},
methods: {
//打开
open() {
this.visible = true;
},
//关闭
close() {
this.visible = false;
},
rotateLeft() {
this.$refs.cropper.rotateLeft()
},
rotateRight() {
this.$refs.cropper.rotateRight()
},
changeScale(num) {
num = num || 1
this.$refs.cropper.changeScale(num)
},
beforeUpload(file) {
this.haveFile = false;
if (file.name.lastIndexOf(".png") > 0
|| file.name.lastIndexOf(".jpg") > 0
|| file.name.lastIndexOf(".jpeg") > 0) {
this.haveFile = true;
} else {
this.options.img = "";
this.$message.error(this.$t("msg.msg001"));
return;
}
const reader = new FileReader()
// 把Array Buffer转化为blob 如果是base64不需要
// 转化为base64
reader.readAsDataURL(file)
reader.onload = () => {
this.options.img = reader.result;
}
// 转化为blob
// reader.readAsArrayBuffer(file)
return false
},
// 上传图片(点击上传按钮)
save() {
this.loading = true;
const _this = this
const formData = new FormData()
this.$refs.cropper.getCropBlob((data) => {
const img = window.URL.createObjectURL(data)
this.model = true
this.modelSrc = img
formData.append('avatarfile', data, this.fileName)
uploadAvatar(formData).then(res => {
if (res.code == 200) {
setLoginUser(res.data);
//this.$message.success("保存成功");
this.$message.success(this.$t("msg.msg002"));
_this.visible = false
this.$emit("ok");
} else {
//this.$message.success("保存失败");
this.$message.error(this.$t("msg.msg003") + res.code);
}
}).finally(() => {
this.loading = false;
});
});
},
realTime(data) {
this.previews = data
}
},
};
</script>
<style lang="less" scoped>
.avatar-upload-preview {
position: absolute;
top: 50%;
left: -5%;
transform: translate(50%, -50%);
width: 180px;
height: 180px;
border-radius: 50%;
box-shadow: 0 0 4px #ccc;
overflow: hidden;
img {
width: 100%;
height: 100%;
}
}
</style>
后台
/**
* 保存头像
*/
@Log(title = "用户信息", businessType = BusinessType.UPDATE)
@PostMapping("/updateAvatar")
@PreAuthorize("hasAuthority('sys:app:all')")
@ResponseBody
public HttpResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
{
String userId = getUserId();
try
{
if (!file.isEmpty())
{
SysUser user = service.selectById(Long.parseLong(userId));
String avatar = FileUploadUtils.upload(ProjectConfig.getAvatarPath(), file);
user.setAvatar(avatar);
if (service.update(user) > 0)
{
user.clearSensitiveField();
return HttpResult.ok(user);
}
return HttpResult.error(10001,"图片上传失败");
}
return HttpResult.error(10002,"未找到要上传图片");
}
catch (Exception e)
{
return HttpResult.error(10003,e.getMessage());
}
}