用 vue 和 elementui 实现文件上传
时间: 2023-12-04 18:00:35 浏览: 33
好的,我会为您解答。
首先,您需要在 Vue.js 中引入 Element-UI 组件库。可以使用以下命令进行安装:
```
npm i element-ui -S
```
然后在 main.js 中引入 Element-UI 的 CSS 和 JS 文件:
```javascript
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
```
接下来,在组件中使用 el-upload 组件来实现文件上传。以下是一个示例:
```vue
<template>
<el-upload
class="upload-demo"
action="/your-upload-api"
:on-success="handleUploadSuccess"
:before-upload="beforeUpload"
:auto-upload="false"
:file-list="fileList">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button size="small" type="success" @click="uploadFiles">上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
}
},
methods: {
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传图片只能是 JPG/PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
handleUploadSuccess(response, file, fileList) {
this.$message.success('上传成功!')
},
uploadFiles() {
this.$refs.upload.submit()
}
}
}
</script>
```
在上面的示例中,我们使用了 el-upload 组件来创建上传组件,可以配置 action 属性来指定上传文件的服务器地址。同时,在 methods 方法中定义了 beforeUpload 和 handleUploadSuccess 两个方法来控制上传文件的规则和上传成功后的处理。最后,在 uploadFiles 方法中,我们调用了 $refs.upload.submit() 方法来触发文件上传。
希望这个回答能对您有所帮助,如果有任何疑问,请随时提出来。