效果图

我的需求的单图片上传,如果读者的需求是多图片。看完本篇之后,根据element文档把vue图片上传的部分代码进行更改就可以
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

前端分析

在弄这个功能之前我是不知道vue有专门FormData类型用于上传文件和数值。但是在简单了解这个类型之后,就可以很快实现上述功能。
首先是创建(点击按钮方法中),不需要提前声明, this.formData = new FormData;
然后是添加属性(上传按钮方法中),this.formData.append('key', value);
最后将整个formData进行传送。
具体代码:
1.上传图片组件

        <!-- 添加或修改获奖信息管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          	<el-row>
       			表单数据部分代码,已省略,按需加入
          	</el-row>
          	<el-row>
			
			<!--     用于标记图片是否已上传         -->
       			<el-col :span="12">
                	<el-form-item label="获奖图片" prop="myIsUpload">
                  	<el-input  disabled v-model="form.myIsUpload" placeholder="未上传"/>
    	            </el-form-item>
              </el-col>
          	</el-row>
          	<el-row>
              <el-col :span="12">
                <el-form-item label-width="80px" label="上传图片">
                  <div  >
                    <!--elementui的form组件-->
                    <el-upload
                      action="#"
                      :show-file-list="false"
                      :auto-upload="false"
                      :multiple="false"
                      :on-change="uploadFile"
                      drag
                      accept="image/jpg,image/jpeg,image/png">
                      <i v-if="imageUrl" class="el-icon-circle-close deleteImg" @click.stop="handleRemove"></i>
                      <img v-if="imageUrl" :src="imageUrl" class="el-upload--picture-car"/>
                      <div v-else>
                        <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
                        <div>上传图片</div>
                        <div>格式为png、jpeg或jpg</div>
                      </div>
                    </el-upload>
                  </div>
                </el-form-item>
              </el-col>
              	 <el-col :span="12">
             	 </el-col>
            </el-row>
          </el-form>
          
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
            

通过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

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :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"
          />
        </div>
      </el-col>


      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['competition:award:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['competition:award:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['competition:award:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['competition:award:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="awardList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="#" align="center" prop="awardId"/>
          <el-table-column label="竞赛组织学院" align="center" prop="deptName"/>
          <el-table-column label="学号" align="center" prop="studentNo"/>
          <el-table-column label="姓名" align="center" prop="studentName"/>
          <el-table-column label="获奖竞赛" align="center" prop="competitionId"/>
          <el-table-column label="项目名称" align="center" prop="projectName"/>
          <el-table-column label="证书编号" align="center" prop="certificateNumber"/>
          <el-table-column label="获奖网址" align="center" prop="awardWebsite"/>
          <el-table-column label="竞赛级别" align="center" prop="competitionLevel"/>
          <el-table-column label="获奖等级" align="center" prop="awardLevel"/>
          <el-table-column label="获奖时间" align="center" prop="awardTime" width="180">

            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.awardTime, '{y}-{m}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="证书图片" align="center" prop="certificateImageUrl" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.certificateImageUrl" :width="50" :height="50"/>
            </template>

          </el-table-column>
          <!--          <el-table-column label="组织机构" align="center" prop="organization">-->
          <!--            <el-upload-->
          <!--              v-model:file-list="fileList"-->
          <!--              class="upload-demo"-->
          <!--              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"-->
          <!--              multiple-->
          <!--              :on-preview="handlePreview"-->
          <!--              :on-remove="handleRemove"-->
          <!--              :before-remove="beforeRemove"-->
          <!--              :limit="3"-->
          <!--              :on-exceed="handleExceed"-->
          <!--            >-->
          <!--              <el-button type="primary">Click to upload</el-button>-->
          <!--            </el-upload>-->
          <!--          </el-table-column>-->
          <el-table-column label="组织机构" align="center" prop="organization"/>
          <el-table-column label="重点竞赛" align="center" prop="isMain"/>
          <el-table-column label="项目涉航空类" align="center" prop="isAviation"/>
          <el-table-column label="竞赛类别" align="center" prop="competitionCategory"/>
          <el-table-column label="属于不降级竞赛" align="center" prop="isDemotion"/>
          <el-table-column label="指导教师1" align="center" prop="teacher1Name"/>
          <el-table-column label="指导教师2" align="center" prop="teacher2Name"/>
          <el-table-column label="指导教师3" align="center" prop="teacher3Name"/>
          <el-table-column label="团队名称" align="center" prop="teamName"/>
          <el-table-column label="学院" align="center" prop="stuDeptName"/>
          <el-table-column label="班级" align="center" prop="stuClassName"/>
          <el-table-column label="年级" align="center" prop="stuGradeName"/>
          <el-table-column label="专业" align="center" prop="stuMajorName"/>


          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['competition:award:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['competition:award:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改获奖信息管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="竞赛名称" prop="competitionId">
                  <el-select v-model="form.competitionId" placeholder="请选择竞赛">
                    <el-option
                      v-for="item in competitionsOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="学号" prop="studentNo">
                  <el-input v-model="form.studentNo" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证书编号" prop="certificateNumber">
                  <el-input v-model="form.certificateNumber" placeholder="请输入证书编号"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="获奖网址" prop="awardWebsite">
                  <el-input v-model="form.awardWebsite" placeholder="请输入获奖网址"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖时间" prop="awardTime">
                  <el-date-picker clearable
                                  v-model="form.awardTime"
                                  type="month"
                                  value-format="yyyy-MM"
                                  placeholder="请选择获奖时间">
                  </el-date-picker>

                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="团队名称" prop="teamName">
                  <el-input v-model="form.teamName" placeholder="请输入团队名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获奖等级" prop="awardLevel">
                  <el-select v-model="form.awardLevel" placeholder="请选择获奖等级">
                    <el-option
                      v-for="item in awardLevels"
                      :key="item"
                      :label="item"
                      :value="item"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="指导教师1" prop="teacher1Name">
                  <el-select v-model="form.teacher1No" placeholder="请选择指导教师1">
                    <el-option
                      v-for="item in teachersOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="指导教师2" prop="teacher2Name">
                  <el-select v-model="form.teacher2No" placeholder="请选择指导教师2">
                    <el-option
                      v-for="item in teachersOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="指导教师3" prop="teacher3Name">
                  <el-select v-model="form.teacher3No" placeholder="请选择指导教师3">
                    <el-option
                      v-for="item in teachersOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
<!--     用于标记图片是否已上传         -->
              <el-col :span="12">
                <el-form-item label="获奖图片" prop="myIsUpload">
                  <el-input  disabled v-model="form.myIsUpload" placeholder="未上传"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label-width="80px" label="上传图片">
                  <div id="upload2">
                    <!--elementui的form组件-->
                    <el-upload
                      action="#"
                      :show-file-list="false"
                      :auto-upload="false"
                      :multiple="false"
                      :on-change="uploadFile"
                      drag
                      accept="image/jpg,image/jpeg,image/png">
                      <i v-if="imageUrl" class="el-icon-circle-close deleteImg" @click.stop="handleRemove"></i>
                      <img v-if="imageUrl" :src="imageUrl" class="el-upload--picture-car"/>
                      <div v-else>
                        <i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c"></i>
                        <div>上传图片</div>
                        <div>格式为png、jpeg或jpg</div>
                      </div>
                    </el-upload>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        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
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
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("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {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`)
    }
  },

//*********************************图片下
};
</script>
<style scoped lang="scss">
.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;
}
</style>

后端分析

后端我用的是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。
不知道有多少同学看到最后呢~

更多推荐