前端elment-ui
<template>
<div class="quanxian">
<el-upload
class="upload-demo"
:action="uploadUrl"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="onSuccess"
:before-remove="beforeRemove"
:before-upload="beforeUpload"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<el-image :src="imagePath" fit="scale-down" style="max-width: 400px; max-height: 400px;"></el-image>
</div>
</div>
</template>
<script>
import api from "@/main";
export default {
beforeRouteEnter(to, from, next) {
next((vm) => {
// vm.getSelectuser();
// vm.getSelectdsc();
});
},
data() {
return {
fileList: [],
uploadUrl: '',
showResult: false,
imagePath: require('@/assets/1693230164098_1.png')
};
},
methods: {
beforeUpload(file) {
// 在上传文件之前的处理逻辑
},
onSuccess(response, file) {
// 上传成功后的处理逻辑
this.showResult = true;
this.filePath = response;
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
},
beforeUpload(file) {
// 1. 创建一个 FormData 对象,并将文件添加到该对象中
const formData = new FormData();
formData.append('file', file);
// 2. 设置请求头
const headers = {
'Content-Type': 'multipart/form-data' // 设置请求头为 multipart/form-data
};
// 3. 发送文件上传请求
api.post('/atmaddress/api/upload', formData)
.then(response => {
// 4. 处理上传成功的响应
console.log(response.data);
})
.catch(error => {
// 5. 处理上传失败的错误
console.error(error);
});
// 6. 返回 false 取消默认的文件上传请求
return false;
}
},
};
</script>
<style>
</style>
后端
@PostMapping("/atmaddress/api/upload")
public String handleUpload(@RequestPart("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 获取原始文件名
String originalFilename = file.getOriginalFilename();
// 设置保存路径为桌面路径
String savePath = "C:\\Users\\李贺森\\Desktop\\新建文件夹\\前端\\sensitivedata\\src\\assets\\";
// 创建保存目录(如果目录不存在的话)
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
// 生成新的文件名
String newFileName = System.currentTimeMillis() + "_" + originalFilename;
// 构造保存文件的路径
String filePath = savePath + newFileName;
// 创建文件对象
File destFile = new File(filePath);
// 将文件写入到保存路径
file.transferTo(destFile);
return "文件保存成功,保存路径为:" + filePath;
} catch (IOException e) {
e.printStackTrace();
return "文件保存失败";
}
} else {
return "上传文件为空";
}
}