前端:
<template>
<div class="ceshi">
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUploada"
>
<img
v-if="coverImg"
:src="coverImg"
class="avatar"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<p style="color: #666; margin-top: 6px; margin-bottom: 12px">
点击添加
</p>
</el-upload>
</div>
</template>
<script>
import {filesArray } from "@/api/curriculum";
export default {
components: {
},
data() {
return {
coverImg:'',
loadingstate: false,
};
},
watch: {
},
methods: {
handleAvatarSuccess(response, file, fileList) {
this.loadingstate = false;
},
beforeAvatarUploada(file) {
this.loadingstate = true;
let index = file.name.lastIndexOf(".");
let extension = file.name.substr(index + 1);
let extensionList = [
"png",
"PNG",
"jpg",
"JPG",
"jpeg",
"JPEG",
"bmp",
"BMP",
];
const isLt2M = file.size / 1024 / 1024 < 10;
if (!isLt2M) {
this.$message({
message: "封面不可超出10M",
type: "warning",
center: true,
});
return false;
} else if (extensionList.indexOf(extension) < 0) {
this.$message({
message: "当前文件格式不支持",
type: "error",
center: true,
});
return false;
} else {
const obj = new FormData();
obj.append("files", file);
filesArray(obj).then((res) => {
if (res.code == 20000) {
this.coverImg='/download?imageName='+res.data;
}
});
}
},
},
created() {
},
};
</script>
<style scoped>
.ceshi{
margin: 50px 600px;
}
img {
width: 200px;
height: 200px;
}
</style>
后端(两个接口)
@PostMapping("/upload/files")
public Result2<?> upload(MultipartFile files){
String originalFilename = files.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
System.out.println(suffix);
String imageName=UUID.randomUUID()+ suffix;
String path="D://img/";
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}
try {
files.transferTo(new File(path+imageName));
} catch (IOException e) {
e.printStackTrace();
}
return Result2.success("成功",imageName);
}
@GetMapping("/download")
public void download(@RequestParam("imageName")String imageName, HttpServletResponse response){
String path="D://img/";
try {
FileInputStream fileInputStream = new FileInputStream(new File(path + imageName));
ServletOutputStream outputStream = response.getOutputStream();
int len=0;
byte[] bytes=new byte[2048];
while ((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}