<template>
<div>
<span id="headImg">头像</span>
<el-upload
class="avatar-uploader"
:http-request="myupload"
action
:auto-upload="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
name="file"
ref="my"
>
<img id="showHead" v-if="imageUrl" :src="imageUrl" class="avatar">
<i style="width: 20px; height: 20px; position: relative; top:-30px; left: 30px" v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
import {request} from "../../network/request";
export default {
data() {
return {
imageUrl: sessionStorage.getItem("imgUrl")
};
},
methods: {
remind(){
alert();
},
handleAvatarSuccess(res, file) {
alert();
console.log(this.imageUrl);
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
uploading(){
this.$refs.my.submit()
},
myupload(content){
let myformData = new FormData()
myformData.append('file',content.file)
request({
url:"/fileUpload",
method: "post",
data:myformData,
}).then(res=>{
console.log(22)
console.log(res.data);
this.question = res.data;
}).catch(err=>{
console.log(err);
});
}
},
mounted() {
document.getElementsByClassName(".el-upload")[0].style.border = "1px dashed #d9d9d9";
}
}
</script>
<style scoped>
#headImg{
text-align: right;
vertical-align: middle;
font-size: 14px;
color: #606266;
line-height: 40px;
padding: 0 12px 0 0;
box-sizing: border-box;
position: relative;
left: 60px;
top: 80px;
}
#showHead{
height: 120px;
width: 120px;
padding: 10px;
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
}
#showHead:hover{
border-color: #409EFF;
}
.avatar-uploader {
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
width: 170px;
margin-left: 100px;
}
.avatar-uploader:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam("file") MultipartFile upload) {
System.out.println("接收到了");
if (upload.isEmpty()) {
System.out.println("文件为空空");
}
String path = "C:/Users/30611/Desktop/upload";
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
String fileType =upload.getOriginalFilename().substring(upload.getOriginalFilename().indexOf("."));
String uuid = UUID.randomUUID().toString().replace("-", "");
String filename = uuid+fileType;
try {
upload.transferTo(new File(path,filename));
} catch (Exception e) {
e.printStackTrace();
}
return "上传成功";
}