el-upload用form的方式多文件上传的方法

使用el-upload组件遇到的坑。

1.第一种感觉最好,首先多个文件是一个http请求,另外还可以传除文件外其他的参数,但是没有进度条了。

发送请求的部分没有注释的部分是我分装了调后台的api,注释的部分是直接调。

注意如果使用自定义提交http-request,则on-success和on-error这两个钩子函数会不起作用,另外点击事件submitUpload中的this.$refs.uploadFiles.submit();是必须的,个人感觉是先将所有的文件给el-form处理,

我发先执行this.$refs.uploadFiles.submit();会多次执行handleUpload函数,次数与要上传文件的个数一样。

fileList: [], files: []要在data中先定义好,file是在form默认有的,是选进来的一个文件。action此时是无用的,但是必须要设置。

<template>
  <el-form>
    <div class="drop-upload-container">
      <el-form-item :label-width="formLabelWidth">
        <el-upload
          multiple
          drag
          ref="uploadFiles"
          :action="action"
          :limit="limit"
          :auto-upload="autoUpload"
          :accept="accept"
          :before-upload="beforeUploadFile"
          :on-remove="handleRemove"
          :on-change="fileChange"
          :on-exceed="exceedFile"
          :http-request="handleUpload"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t(‘upload.uploadText‘) }}
            <em>{{ $t(‘upload.clickUpload‘) }}</em>
          </div>
          <div class="el-upload__tip" slot="tip">{{ $t(‘upload.uploadFileType‘) }}</div>
        </el-upload>
      </el-form-item>
      <el-form-item class="item-container">
        <el-button
          size="small"
          type="primary"
          @click.native="submitUpload"
        >{{ $t(‘buttonTitle.okTitle‘) }}</el-button>
        <el-button size="small" @click.native="uploadCancle">{{ $t(‘buttonTitle.cancleTitle‘) }}</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import { stringFormat } from "@/utils/stringutils";
import axios from "axios";
import { uploadFilesReq } from "@/api/upload";

export default {
  name: "Upload",
  props: {
    action: {
      required: true,
      type: String
    },
    limit: {
      required: true,
      type: Number
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    accept: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      formLabelWidth: "80px",
      userIds: sessionStorage.getItem("userid"),
      fileList: [],
      files: []
    };
  },
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      console.log("===exceed===");
      let limit_num = `${this.limit}`;
      let total_num = `${files.length + fileList.length}`;

      this.$notify.warning({
        title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
        //message: `只能选择 ${this.limit} 个文件,当前共选择了 ${files.length + fileList.length} 个`
        message: stringFormat(
          this.$i18n.t("uploadDialogMsg.uploadFilesLimit"),
          [`${this.limit}`, `${files.length + fileList.length}`]
        )
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log("===change===");
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
    beforeUploadFile(file) {
      console.log("before upload");
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isAcceptFiles =
        extension === "xlsx" ||
        extension === "vue" ||
        extension === "png" ||
        extension === "PNG";
      if (!isAcceptFiles) {
        this.$notify.warning({
          title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
          message: this.$i18n.t("uploadDialogMsg.uploadFilesType")
        });
      }

      let size = file.size / 1024 / 1024;
      const isAcceptSize = size < 10;
      if (!isAcceptSize) {
        this.$notify.warning({
          title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
          message: this.$i18n.t("uploadDialogMsg.uploadFilesSize")
        });
      }
      return isAcceptFiles && isAcceptSize;
    },
    // 点击x时执行的钩子函数
    handleRemove(file, fileList) {
      console.log("===remove===");
    },

    handleUpload(raw) {
      this.files.push(raw.file);
    },
    submitUpload() {
      this.$refs.uploadFiles.submit();
      let fd = new FormData();
      fd.append("userIds", this.userIds);
      this.files.forEach(file => {
        fd.append("file", file, file.name);
      });

      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };

      uploadFilesReq(fd, config)
        .then(res => {
          console.log("===upload rep===");
          console.log(res);
          if (res.data.status === "success") {
            this.$notify.success({
              title: this.$i18n.t("dialogTitle.dialogSuccessTitle"),
              message: this.$i18n.t("uploadDialogMsg.uploadFilesSuccess")
            });
          } else {
            this.$notify.error({
              title: this.$i18n.t("dialogTitle.dialogErrorTitle"),
              message: this.$i18n.t("uploadDialogMsg.uploadFilesFailed")
            });
          }
        })
        .catch(err => {
          console.log("===upload error===");
          console.log(err);
          this.$notify.error({
            title: this.$i18n.t("dialogTitle.dialogErrorTitle"),
            message: this.$i18n.t("uploadDialogMsg.uploadFilesFailed")
          });
        });

      // axios
      //   .post("/uploadFiles/pc/job/uploadFile", fd, config, {
      //     timeout: 60000 * 3
      //   })
      //   .then(res => {
      //     if (res.data.status === "success") {
      //       this.$notify.success({
      //         title: this.$i18n.t("dialogTitle.dialogSuccessTitle"),
      //         message: this.$i18n.t("uploadDialogMsg.uploadFilesSuccess")
      //       });
      //     }else{
      //       this.$notify.error({
      //       title: this.$i18n.t("dialogTitle.dialogErrorTitle"),
      //       message: this.$i18n.t("uploadDialogMsg.uploadFilesFailed")
      //     });
      //     }
      //   })
      //   .catch(err => {
      //     this.$notify.error({
      //       title: this.$i18n.t("dialogTitle.dialogErrorTitle"),
      //       message: this.$i18n.t("uploadDialogMsg.uploadFilesFailed")
      //     });
      //   });
    },
    uploadCancle() {
      console.log("===Cancle===");
      this.$refs.uploadFiles.clearFiles();
    }
  }
};
</script>

<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
  border: 2px dashed #bbb;
  width: 600px;
  /* height: 160px; */
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
.drop-upload-container {
  width: 450px;
}
.item-container {
  margin: 0 auto;
  /* text-align: center; */
  padding-left: 80px;
}
</style>

上传文件调用后台api的封装

import Axios from ‘@/axios‘

export function uploadFilesReq(fd, config) {
  return Axios.post("/uploadFiles/pc/job/uploadFile", fd, config, {
    timeout: 60000 * 3
  });
}

上传文件组件的调用

<template>
  <div class="app-container">
    <upload
    :action="action"
    :limit="limitNum"
    :accept="accept"
    :auto-upload="autoUpload"
    />
  </div>
</template>

<script>
// import Upload from "@/components/Upload";

import Upload from "./upload";

export default {
  name: ‘UploadFiles‘,
  components: { Upload },
  data() {
    return {
      action: ‘/uploadFiles/pc/job/uploadFile‘,
      limitNum: 3,
      accept: ".xlsx,.vue,.png,PNG",
      autoUpload: false
    }
  },
  methods: {

  }
}
</script>

2.第二中每个文件都会发送一个请求,并且不能加其他的参数,但是有进度条。

action此时有用的,必须要设置,on-success和on-error这两个钩子函数会起作用

<template>
  <el-form>
    <div class="drop-upload-container">
      <el-form-item :label-width="formLabelWidth">
        <el-upload
          multiple
          drag
          ref="uploadFiles"
          :action="action"
          :limit="limit"
          :auto-upload="autoUpload"
          :accept="accept"
          :before-upload="beforeUploadFile"
          :on-remove="handleRemove"
          :on-change="fileChange"
          :on-exceed="exceedFile"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t(‘upload.uploadText‘) }}
            <em>{{ $t(‘upload.clickUpload‘) }}</em>
          </div>
          <div class="el-upload__tip" slot="tip">{{ $t(‘upload.uploadFileType‘) }}</div>
        </el-upload>
      </el-form-item>
      <el-form-item class="item-container">
        <el-button
          size="small"
          type="primary"
          @click.native="submitUpload"
        >{{ $t(‘buttonTitle.okTitle‘) }}</el-button>
        <el-button size="small" @click.native="uploadCancle">{{ $t(‘buttonTitle.cancleTitle‘) }}</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import { stringFormat } from "@/utils/stringutils";
import axios from ‘axios‘

export default {
  name: "Upload",
  props: {
    action: {
      required: true,
      type: String
    },
    limit: {
      required: true,
      type: Number
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    accept: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      formLabelWidth: "80px",
      userIds: sessionStorage.getItem("userid"),
      fileList: [],

      files: []
    };
  },
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      let limit_num = `${this.limit}`;
      let total_num = `${files.length + fileList.length}`;

      this.$notify.warning({
        title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
        message: stringFormat(this.$i18n.t("uploadDialogMsg.uploadFilesLimit"),
          [`${this.limit}`, `${files.length + fileList.length}`]
        )
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      console.log("===change===");
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
    beforeUploadFile(file) {
      console.log("before upload");
      console.log(file);
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isAcceptFiles =
        extension === "xlsx" ||
        extension === "vue" ||
        extension === "png" ||
        extension === "PNG";
      if (!isAcceptFiles) {
        this.$notify.warning({
          title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
          message: this.$i18n.t("uploadDialogMsg.uploadFilesType")
        });
      }

      let size = file.size / 1024 / 1024;
      const isAcceptSize = size < 10;
      if (!isAcceptSize) {
        this.$notify.warning({
          title: this.$i18n.t("dialogTitle.dialogWarningTitle"),
          message: this.$i18n.t("uploadDialogMsg.uploadFilesSize")
        });
      }
      return isAcceptFiles && isAcceptSize;
    },
    // 点击x时执行的钩子函数
    handleRemove(file, fileList) {
      console.log("===remove===");
    },
    // 文件上传成功时的钩子
    handleSuccess() {
      this.$notify.success({
        title: this.$i18n.t("dialogTitle.dialogSuccessTitle"),
        message: this.$i18n.t("uploadDialogMsg.uploadFilesSuccess")
      });
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: this.$i18n.t("dialogTitle.dialogErrorTitle"),
        message: this.$i18n.t("uploadDialogMsg.uploadFilesFailed")
      });
    },
    handleUpload(raw) {
      this.files.push(raw.file);
    },
    submitUpload() {
      console.log(this.form.userIds);
      this.$refs.uploadFiles.submit();
    },
    uploadCancle() {
      console.log("=========uploadFile=========");
      this.$refs.uploadFiles.clearFiles();
    }
  }
};
</script>

<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
  border: 2px dashed #bbb;
  width: 600px;
  /* height: 160px; */
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
.drop-upload-container {
  width: 450px;
}
.item-container {
  margin: 0 auto;
  /* text-align: center; */
  padding-left: 80px;
}
</style>

原文地址:https://www.cnblogs.com/wang-liang-blogs/p/12101371.html

时间: 2024-08-07 02:31:59

el-upload用form的方式多文件上传的方法的相关文章

以调用接口的方式将文件上传至Web服务器

前台代码: <form id="form1" action="http://www.abc.com/data/UploadFile.aspx" method="post" enctype="multipart/form-data" > <input type="file" name="F" style="width:160px;" /> <

我爱Java系列---【SpringMVC传统方式的文件上传和前端获取数据库图片在页面显示】

一.文件上传 说明:传统方式的文件上传,指的是我们上传的文件和访问的应用存在于同一台服务器上.并且上传完成之后,浏览器可能跳转. 1. 第一步:创建 maven 工程并导入 commons-fileupload 坐标 1 <dependency> 2 <groupId>commons-fileupload</groupId> 3 <artifactId>commons-fileupload</artifactId> 4 <version&g

ANDROID使用MULTIPARTENTITYBUILDER实现类似FORM表单提交方式的文件上传

最近在做 Android 端文件上传,要求采用 form 表单的方式提交,项目使用的 afinal 框架有文件上传功能,但是始终无法与php写的服务端对接上,无法上传成功.读源码发现:afinal 使用了某大神写的 MultipartEntity.java 生成 form 表单内容,然而生成的内容格式不够标准,而且还存在诸多问题,如:首先将所有文件读入到内存,再生成字节流写入到 socket.那么问题来了:如果是几百MB的文件怎么办? 几番搜索,受到 这篇文章(已被我转载,但是示例代码已过期)的

使用Anthem.NET 1.5中的FileUpload控件实现Ajax方式的文件上传

Anthem.NET刚刚发布了其最新的1.5版本,其中很不错的一个新功能就是对文件上传功能的Ajax实现.本文将简要介绍一下该功能的使用方法. Anthem.NET的下载与安装 Anthem.NET可以在此下载:http://sourceforge.net/project/showfiles.php?group_id=151897&package_id=168043&release_id=493609 下载之后解压缩至硬盘中的某一目录中,编译项目得到Anthem.dll.然后将其拷贝到We

SpringMVC注解方式与文件上传

目录: springmvc的注解方式 文件上传(上传图片,并显示) 一.注解 在类前面加上@Controller 表示该类是一个控制器在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上 将上一篇的博客改为注解方式: SpringMVC的基础配置及视图定位 1.修改springmvc-servlet.xml 去掉映射相关的配置,因为已经使用注解方式了增加 <context:component-scan

WebApi实现Ajax模拟Multipart/form-data方式多文件上传

前端页面代码: <input type="file" class="file_control" /><br /> <input type="file" class="file_control" /><br /> <input type="file" class="file_control" /> <button id=&q

AJAX提交form表单带文件上传

过了三天才想要写博客,这样不好,要改正 在做毕设的时候,用户发帖涉及到了文件上传的问题,在这里记录一下 背景: 在用户发帖的时候,用户只想发表文字postText,还有些用户想在发表postText的同时还发表一些图片,如何做? 上代码 不写的太细了,和流水账似的,挑重点记录一下. 1.前台的文件上传 本来想用form表单直接上传了,但是form提交时会刷新整个页面,但这不是我想要的,所以使用了ajax提交form表单. 利用ajax提交表单需要用到jquery.form.js这个包,网上有很多

文件上传+绕过方法+菜刀的基本用法

关于原理方面就不加赘述了,可以Google一下,我贴一下几百年前我的理解:原理:上传一个脚本(jsp,asp,php),然后就得到机子的shell (哇,感觉很粗糙) 文件上传漏洞的几种常见的姿势: 1.js前端验证2.mime3.后缀名4.修改字母大小写(同第一种,就是把PHP几种大小写试一试 还有可能是phtml)5.00截断6.上传含有一句话的图片 最简单的:先直接上传一个php文件,看是否正确 1.js前端验证: 一般都是在网页上写一段JavaScript脚本,校验上传文件的后缀名,有白

ajaxFileUpload.js插件支持多文件上传的方法

前提条件:ajaxFileUpload.js插件多文件上传步骤:1.修改源码,(源码只支持单个文件的上传):复制代码 代码如下: //修改前代码------- //var oldElement = jQuery('#' + fileElementId); //var newElement = jQuery(oldElement).clone(); //jQuery(oldElement).attr('id', fileId); //jQuery(oldElement).before(newEle