el-upload上传pdf文件
时间: 2023-11-21 22:56:20 浏览: 71
以下是使用Element UI中的el-upload组件上传pdf文件的示例代码:
```html
<template>
<el-upload
class="upload-demo"
action="/upload"
:on-change="handleChange"
:before-upload="beforeUpload"
:file-list="fileList"
:accept="'application/pdf'"
:limit="1"
:on-exceed="handleExceed"
:show-file-list="false"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传pdf文件,且不超过1个</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
};
},
methods: {
handleChange(file, fileList) {
console.log(file, fileList);
},
beforeUpload(file) {
const isPDF = file.type === 'application/pdf';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isPDF) {
this.$message.error('上传文件只能是pdf格式!');
}
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
}
return isPDF && isLt2M;
},
handleExceed(files, fileList) {
this.$message.warning(`只能上传一个pdf文件!`);
}
}
};
</script>
```
在上述代码中,我们使用了Element UI中的el-upload组件来实现文件上传功能。其中,我们通过设置accept属性为'application/pdf'来限制只能上传pdf文件,通过设置limit属性为1来限制只能上传一个文件,通过设置show-file-list属性为false来隐藏文件列表。在beforeUpload方法中,我们对上传的文件进行了格式和大小的限制,如果不符合要求则会弹出错误提示。在handleChange方法中,我们可以获取到上传的文件信息。