html代码:

<template>
    <el-dialog :fullscreen="false" title="添加" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="100px">
          
          <el-form-item label="附件上传" v-if="showFile">
            <el-upload class="upload-demo" action="" :on-preview="handlePreview" :on-remove="handleRemove"
              :before-remove="beforeRemove" multiple ref="upload" :limit="3" :on-exceed="handleExceed" :file-list="fileList"
              :on-change="OnChange" :auto-upload="false">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
  </template>

data:

 data() {
      return {
        fileList: [],
      };
 },

api接口:

// 附件上传
export function uploadFilePort (data) {
    return request({
        url: api + "/uploadFile",
        method: 'post',
        headers: {
            "Content-Type": "multipart/form-data"
        },
        data
    })
}

methods:

 methods: {
        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}?`);
        },

        // 提交
        submit() {
            var newFile = new FormData();
            this.fileList.forEach((item, index) => {
                newFile.append("file", item.raw)
            })
            // 调用上传文件api发送上传文件请求
            uploadFilePort(newFile).then(
                (res) => {
                    console.log("文件上传res", res);
                    if (res.data.code == 200) {
                        this.$message({
                            message: "添加成功!!",
                            type: "success",
                        });
                    }
                },
                (err) => {
                    this.$message.error(err);
                }
            );
        },
        // 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
        OnChange(file, fileList) {
            console.log("OnChange-fileList", file, fileList);
            this.fileList = fileList;
        },
       
    },

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐