使用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.files = [];
       this.$refs.uploadFiles.clearFiles();
       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>

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

  1. WordPress Contact Form 7插件任意文件上传漏洞

    漏洞名称: WordPress Contact Form 7插件任意文件上传漏洞 CNNVD编号: CNNVD-201311-415 发布时间: 2013-11-28 更新时间: 2013-11-28 ...

  2. IIS7.5修改asp的文件上传限制方法

    第一.IIS7.5修改asp的文件上传限制方法 1.打开IIS 2.打开面板中的应用程序开发 asp 3.找到最后的限制属性 4.修改其中的最大请求实体主体限制的值:默认为200000字节,等于195 ...

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

    最近在做 Android 端文件上传,要求采用 form 表单的方式提交,项目使用的 afinal 框架有文件上传功能,但是始终无法与php写的服务端对接上,无法上传成功.读源码发现:afinal 使 ...

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

    Anthem.NET刚刚发布了其最新的1.5版本,其中很不错的一个新功能就是对文件上传功能的Ajax实现.本文将简要介绍一下该功能的使用方法. Anthem.NET的下载与安装 Anthem.NET可 ...

  5. form+iframe实现ajax文件上传

    在做文件上传时除了传入文件外,还有附件参数,并且要求不刷新页面,之前是表单提交的方式,现在修改成ajax上传的方式,由于没有选择用插件,所以用form+iframe的方式,并且这种方式对IE8以上及主 ...

  6. SpringMVC注解方式与文件上传

    目录: springmvc的注解方式 文件上传(上传图片,并显示) 一.注解 在类前面加上@Controller 表示该类是一个控制器在方法handleRequest 前面加上 @RequestMap ...

  7. php+form表单的文件上传

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...

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

    前端页面代码: <input type="file" class="file_control" /><br /> <input t ...

  9. form表单多文件上传

    1.html/jsp主页 <%@ page language="java" contentType="text/html; charset=UTF-8" ...

随机推荐

  1. logger模块和re模块总结

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,loggin ...

  2. 《PHP程序员面试笔试宝典》——如果面试问题曾经遇见过,是否要告知面试官?

    如何巧妙地回答面试官的问题? 本文摘自<PHP程序员面试笔试宝典> 面试中,大多数题目都不是凭空想象出来的,而是有章可循,只要求职者肯花时间,耐得住寂寞,复习得当,基本上在面试前都会见过相 ...

  3. 06 jQuery

    BOM和DOM 1. 什么是BOM和DOM 到目前为止,我们已经学过了JavaScript的一些简单的语法.但是这些简单的语法,并没有和浏览器有任何交互. 也就是我们还不能制作一些我们经常看到的网页的 ...

  4. 基于zynq XC7Z100 FMC接口通用计算平台

    1.板卡概述 此板卡是北京太速研发,由SoC XC7Z100-2FFG900I芯片来完成卡主控及数字信号处理,XC7Z100内部集成了两个ARM Cortex-A9核和一个kintex 7的FPGA, ...

  5. 通过JAVA对FTP服务器连接,上传,下载,读取,移动文件等

    记录一次对FTP服务器文件内容 通过Java程序对FTP服务器文件处理:连接,上传,下载,读取,移动文件等. 需求描述:今天接到一个任务,在Java项目中,读取FTP服务器上的一些文件,进行一些业务操 ...

  6. python对文件夹内文件去重

    昨天无聊写了一个百度图片爬虫,测试了一下搜索"斗图".一下给我下了3000多个图片,关键是有一半以上重复的.what a fuck program ! 好吧,今天写一个文件去重功能 ...

  7. 好久没写作业了,因为组里分配了任务,学习了Resnet和DenseNet,把概要po上来和大家分享。

    Res: 学长说,不要看别人的博客.看多了就看傻了!俗话说,不听老人言,吃亏在眼前. 第一篇论文来咯!Deep Residual Learning for Image Recognition!国人写的 ...

  8. RFC2544优化步长测试——信而泰网络测试仪实操

    一.测试拓扑 拓扑说明 1.测试仪两个端口和DUT两个端口相连 2.测试仪P1端口发出流量,经过DUT转发后,从B端口发出,进入测试仪P2端口. 二.测试思路 1.在测试仪端口上创建两个Interfa ...

  9. 『无为则无心』Python日志 — 66、将日志信息保存到文件中

    目录 1.把日志信息保存到文件中 2.拓展 (1)观察代码 (2)提出问题 (3)问题说明 1.把日志信息保存到文件中 代码如下所示: """ logging模块是Pyt ...

  10. Qt:QListWidget

    0.说明 QListWidget指明一个基于Item的List Widget. 构造 QListWidget与QListView类似,都可以显示一列Item,区别在于前者可以往其中增删Item. QL ...