文章目录
效果图前端分析完整代码
后端分析修改功能的坑
效果图
我的需求的单图片上传,如果读者的需求是多图片。看完本篇之后,根据element文档把vue图片上传的部分代码进行更改就可以
前端分析
在弄这个功能之前我是不知道vue有专门FormData类型用于上传文件和数值。但是在简单了解这个类型之后,就可以很快实现上述功能。 首先是创建(点击按钮方法中),不需要提前声明, this.formData = new FormData; 然后是添加属性(上传按钮方法中),this.formData.append('key', value); 最后将整个formData进行传送。 具体代码: 1.上传图片组件
表单数据部分代码,已省略,按需加入
action="#" :show-file-list="false" :auto-upload="false" :multiple="false" :on-change="uploadFile" drag accept="image/jpg,image/jpeg,image/png">
通过el-upload的属性 :on-change="uploadFile",可知选择图片后调用的函数:
// 上传图片
uploadFile(item) {
this.imageUrl = URL.createObjectURL(item.raw); // 图片上传浏览器回显地址
console.log(this.imageUrl, "imageUrl")
console.log(this.formData, "formData")
this.$set(this.form, 'myIsUpload', "已上传");
// 将图片信息加入到formData中
this.formData.append('file', item.raw, item.name);
},
handleRemove() {
this.imageUrl = ""
},
讲解:item记录了上传图片的信息 this.$set(this.form, 'myIsUpload', "已上传");的作用是标记此图片已上传,至于标记为什么用this.$set,请看这篇:https://blog.csdn.net/zhang8907xiaoyue/article/details/108289603 this.formData.append('file', item.raw, item.name); 将图片信息加入到formData中
---------------------------------------------分界线--------------------------------------------- 通过确定按钮可知: @click="submitForm",提交函数: 分析: 我们表单的数据目前是存储在form中的,但是我们最终是用formData上传,所以需要将form中的属性全部加入到formData中。 加入之后,根据修改或是新增,调用相应的网络请求函数: updateAward(this.formData) addAward(this.formData)
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
for (let key in this.form) {
if (this.form.hasOwnProperty(key)) {
if (!this.formData.has(key) && this.form[key] != 'null' && this.form[key] != null)
this.formData.append(key, this.form[key]);
}
}
if (valid) {
if (this.form.awardId != null) {
updateAward(this.formData).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
this.formData = null;
this.form.myIsUpload = null;
});
} else {
addAward(this.formData).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
this.formData = null;
this.form.myIsUpload = null;
});
}
}
});
},
/** 修改按钮操作 */
handleUpdate(row) {
this.formData = new FormData;
// 初始化图片
this.imageUrl = row.certificateImageUrl;
this.reset();
const awardId = row.awardId || this.ids
getAward(awardId).then(response => {
this.form = response.data;
this.open = true;
this.title = "修改获奖信息管理";
});
}
网络请求函数: 注意不要加headers,网上有些答案是加入了这个,但也有很多加入了报错。
// 新增获奖信息管理
export function addAward(data) {
return request({
url: '/competition/award',
method: 'post',
data: data,
// headers: {
// 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq'
// }
})
}
// 修改获奖信息管理
export function updateAward(data) {
return request({
url: '/competition/award',
method: 'put',
data: data
})
}
完整代码
vue
v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
:data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
label-width="68px"> v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['competition:award:add']" >新增
type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['competition:award:edit']" >修改
type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['competition:award:remove']" >删除
type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" >导入
type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['competition:award:export']" >导出
{{ parseTime(scope.row.awardTime, '{y}-{m}') }}
size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['competition:award:edit']" >修改
size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['competition:award:remove']" >删除
v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> v-for="item in competitionsOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > v-model="form.awardTime" type="month" value-format="yyyy-MM" placeholder="请选择获奖时间"> v-for="item in awardLevels" :key="item" :label="item" :value="item" :disabled="item.disabled" > v-for="item in teachersOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > v-for="item in teachersOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > v-for="item in teachersOption" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > action="#" :show-file-list="false" :auto-upload="false" :multiple="false" :on-change="uploadFile" drag accept="image/jpg,image/jpeg,image/png">
ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag >
是否更新已经存在的用户数据
仅允许导入xls、xlsx格式文件。
@click="importTemplate">下载模板
import {
listAward,
getAward,
delAward,
addAward,
updateAward,
getTeacher,
getCompetition
} from "@/api/competition/award";
import {deleteComImg, getCompetitionImg} from "@/api/competition/Information";
import {getToken} from "@/utils/auth";
import {deptTreeSelect} from "@/api/system/user";
export default {
name: "Award",
data() {
return {
// 上传图片
formData: "",
imageUrl: "",
orderId: "",
userId: "",
userName: "",
// 导入*************
// 用户导入参数
upload: {
// 是否显示弹出层(用户导入)
open: false,
// 弹出层标题(用户导入)
title: "",
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 0,
// 设置上传的请求头部
headers: {Authorization: "Bearer " + getToken()},
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/competition/award/importData"
},
// 导入*************
// 树形
deptOptions: undefined,
deptName: undefined,
defaultProps: {
children: "children",
label: "label"
},
// 获奖等级
awardLevels: [
"国家级一等奖",
"国家级二等奖",
"国家级三等奖",
"国家级优秀奖",
"省级一等奖",
"省级二等奖",
"省级三等奖",
"省级优秀奖",
],
teachersOption: [],
competitionsOption: [],
// 遮罩层
loading: true,
// 选中数组
ids: [],
// 非单个禁用
single: true,
// 非多个禁用
multiple: true,
// 显示搜索条件
showSearch: true,
// 总条数
total: 0,
// 获奖信息管理表格数据
awardList: [],
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// formData: null,
// 查询参数
queryParams: {
deptId: null,
pageNum: 1,
pageSize: 10,
competitionId: null,
projectName: null,
studentId: null,
studentNo: null,
certificateNumber: null,
awardWebsite: null,
competitionLevel: null,
awardLevel: null,
awardTime: null,
certificateImageUrl: null,
teacher3No: null,
teacher2No: null,
teamName: null,
teacher1No: null,
},
// 表单参数
form: {
},
// 表单校验
rules: {
competitionId: [
{required: true, message: "竞赛名称不能为空", trigger: "blur"}
],
projectName: [
{required: true, message: "项目名称不能为空", trigger: "blur"}
],
studentNo: [
{required: true, message: "学号不能为空", trigger: "blur"}
],
certificateNumber: [
{required: true, message: "证书编号不能为空", trigger: "blur"}
],
awardWebsite: [
{required: true, message: "获奖网址不能为空", trigger: "blur"}
],
competitionLevel: [
{required: true, message: "竞赛级别不能为空", trigger: "change"}
],
awardLevel: [
{required: true, message: "获奖等级不能为空", trigger: "change"}
],
awardTime: [
{required: true, message: "获奖时间不能为空", trigger: "blur"}
],
myIsUpload: [
{required: true, message: "请上传图片", trigger: "input"}
],
},
// -------------------图片
number: 0,
uploadList: [],
dialogImageUrl: "",
dialogVisible: false,
hideUpload: false,
baseUrl: process.env.VUE_APP_BASE_API,
uploadImgUrl: process.env.VUE_APP_BASE_API + "/competition/image/multiPicturesUpload", // 上传的图片服务器地址
headers: {
Authorization: "Bearer " + getToken(),
awardId: -1,
},
fileList: [],
// -------------------图片
};
},
created() {
this.getList();
this.getTeachers();
this.getCompetitions();
this.getDeptTree();
},
methods: {
// 图片上传
// 上传图片
uploadFile(item) {
// this.formData = item.raw; // 图片文件
this.imageUrl = URL.createObjectURL(item.raw); // 图片上传浏览器回显地址
console.log(this.imageUrl, "imageUrl")
console.log(this.formData, "formData")
this.formData = new FormData;
this.$set(this.form, 'myIsUpload', "已上传");
this.formData.append('file', item.raw, item.name);
},
handleRemove() {
this.imageUrl = ""
},
// 导入**************
/** 导入按钮操作 */
handleImport() {
this.upload.title = "用户导入";
this.upload.open = true;
},
/** 下载模板操作 */
importTemplate() {
this.download('/competition/award/importTemplate', {}, `获奖信息导入模板_${new Date().getTime()}.xlsx`)
},
// 文件上传中处理
handleFileUploadProgress(event, file, fileList) {
this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
this.upload.open = false;
this.upload.isUploading = false;
this.$refs.upload.clearFiles();
this.$alert("
", "导入结果", {dangerouslyUseHTMLString: true});this.getList();
},
// 提交上传文件
submitFileForm() {
this.$refs.upload.submit();
},
// 导入**************
//树形***************
// 筛选节点
filterNode(value, data) {
if (!value) return true;
return data.label.indexOf(value) !== -1;
}
,
// 节点单击事件
handleNodeClick(data) {
this.queryParams.deptId = data.id;
this.handleQuery();
}
,
/** 查询部门下拉树结构 */
getDeptTree() {
deptTreeSelect().then(response => {
this.deptOptions = response.data;
});
}
,
//树形***************
getTeachers() {
getTeacher().then(res => {
this.teachersOption = res.optionInfos;
})
}
,
getCompetitions() {
getCompetition().then(res => {
this.competitionsOption = res.optionInfos;
})
}
,
/** 查询获奖信息管理列表 */
getList() {
this.loading = true;
listAward(this.queryParams).then(response => {
this.awardList = response.rows;
this.total = response.total;
this.loading = false;
});
}
,
// 取消按钮
cancel() {
this.open = false;
this.reset();
}
,
// 表单重置
reset() {
this.form = {
awardId: null,
competitionId: null,
projectName: null,
studentId: null,
studentNo: null,
certificateNumber: null,
awardWebsite: null,
competitionLevel: null,
awardLevel: null,
awardTime: null,
certificateImageUrl: null,
teacher3No: null,
teacher2No: null,
teamName: null,
teacher1No: null
};
this.resetForm("form");
}
,
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
}
,
/** 重置按钮操作 */
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
}
,
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map(item => item.awardId)
this.single = selection.length !== 1
this.multiple = !selection.length
}
,
/** 新增按钮操作 */
handleAdd() {
console.log("-- " + this.form.myIsUpload);
// 初始化图片
this.handleRemove();
this.reset();
this.open = true;
this.title = "添加获奖信息管理";
}
,
/** 修改按钮操作 */
handleUpdate(row) {
// 初始化图片
// console.log(row.certificateImageUrl);
this.imageUrl = row.certificateImageUrl;
this.reset();
const awardId = row.awardId || this.ids
getAward(awardId).then(response => {
this.form = response.data;
this.open = true;
this.title = "修改获奖信息管理";
});
}
,
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
for (let key in this.form) {
if (this.form.hasOwnProperty(key)) {
if (!this.formData.has(key) && this.form[key] != 'null' && this.form[key] != null)
this.formData.append(key, this.form[key]);
}
}
if (valid) {
if (this.form.awardId != null) {
updateAward(this.formData).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
this.formData = null;
this.form.myIsUpload = null;
});
} else {
addAward(this.formData).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
this.formData = null;
this.form.myIsUpload = null;
});
}
}
});
}
,
/** 删除按钮操作 */
handleDelete(row) {
const awardIds = row.awardId || this.ids;
this.$modal.confirm('是否确认删除获奖信息管理编号为"' + awardIds + '"的数据项?').then(function () {
return delAward(awardIds);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {
});
}
,
/** 导出按钮操作 */
handleExport() {
this.download('competition/award/export', {
...this.queryParams
}, `award_${new Date().getTime()}.xlsx`)
}
},
//*********************************图片下
};
.upload-file-uploader {
margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
border: 1px solid #e4e7ed;
line-height: 2;
margin-bottom: 10px;
position: relative;
}
.upload-file-list .ele-upload-list__item-content {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
.ele-upload-list__item-content-action .el-link {
margin-right: 10px;
}
后端分析
后端我用的是Minio存储,但是具体大家如何存储就看需求了,存储方便比较简单,但是一定注意一个点
不要在实体类(Award)前加@RequestBody注解,要在MultipartFile 前加@RequestParam注解
@PostMapping
public AjaxResult add(Award award, @RequestParam("file") MultipartFile file) {
存储图片的代码
return toAjax(awardService.insertAward(award));
}
修改功能的坑
如果按上面代码,那么在修改时会遇到两个问题: 1:点击修改,前端提示没有上传图片 2:如果1解决,后端会提示“MultipartFile为空请求地址异常Required request part ‘file’ is not present” 解决方案: 1:原因是我们用了一个属性对是否已经上传文件进行标记,可以在实体类中写一个属性 之前我曾尝试这样解决: 但是不行,我也没有深究。如果有了解的同学,请留言啊~
2:如果在修改数据时,没有重新上传图片,那么file肯定是空的,因为我是在上传图片的方法中将file加入到formData里面的。可以在controller设置一下
写这个小功能我踩了不少坑,也看了很多博客,最后总结解决了这个问题,虽然是小功能,但花了不少时间解决BUG。 不知道有多少同学看到最后呢~
发表评论