1. 实现如下功能
2. 首先添加Upload组件
<el-upload
action="#"
show-file-list
:auto-upload="false"
:multiple="false"
:on-change="handlePreview">
<el-button size="small" type="primary">附件上传</el-button>
<span slot="tip">
请上传doc、docx、xls、xlxs、ppt、pptx、pdf、zip、rar格式类型文件,且大小不超过50M
</span>
</el-upload>
3. 当上传文件发生改变的时候触发on-change事件
//文件发生改变时触发,this.file 是自己定义的变量对象
handlePreview(file, fileList) {
this.file = {};
if (file !== {}) {
//判断选择的类型是否符合筛选条件,如果符合就把值赋给this.file,如果不符合就删除下方显示的文件
uploadCheck(file.raw) ? this.file = file.raw : fileList.splice(fileList.length - 1, 1);
}
//如果this.file不为空,那么就添加进自己定义的数组this.fileList中去(只上传一个文件的话,此步可以省略)
if (this.file !== {}) {
this.fileList.push(this.file)
}
this.file = {};
},
/**
* 上传文件过滤
* @param file
* @returns {boolean}
*/
export function uploadCheck(file) {
const split = file.name.split('.')
const array = []
// 支持的文件格式
array.push('doc')
array.push('xlsx')
array.push('xls')
array.push('pdf')
array.push('ppt')
array.push('pptx')
array.push('docx')
array.push('zip')
array.push('rar')
if (!array.includes(split[split.length - 1])) {
Vue.prototype.$message.error('不支持上传该格式文件!')
return false;
}
if (file.size / 1024 / 1024 > 50) {
Vue.prototype.$message.error('上传文件大小不能超过50M!')
return false;
}
return true;
}
4. 点击确定按钮上传文件
let length = 0;
if (this.fileList.length > 0) {
this.fileList.forEach(function (items) {
//创建一个FormData对象用来储存文件
let formData = new FormData();
//添加文件items,起名为file
formData.append("file", items);
//传参到后端
upload(formData);
length = length + 1;
})
}
5. 后端controller 用MultipartFile对象接收,在实现类里面进行逻辑处理
public Result upload(MultipartFile file) {
//获取传下来的file的名称
String newName = file.getOriginalFilename();
//获取配置文件里面的路径
String path = "C:\\Users\\lenovo\\Desktop";
String newPath = path + "\\" + newName;
//没有对应的文件夹就创建
File filePath = new File(path);
if (!filePath.exists()) {
filePath.mkdirs();
}
try {
file.transferTo(new File(newPath));//上传文件操作
return ResultUtil.success();
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
return ResultUtil.error(ResultCode.FAIL.getCode(), "上传出错!");
}
}
到此我们上传文件的操作就解决了,小伙伴们觉着有用的话就点赞+收藏+转发吧!