vue3使用element-plus上传附件
时间: 2023-07-18 22:11:00 浏览: 145
要在Vue3中使用Element Plus进行附件上传,可以按照以下步骤进行操作:
1. 首先,需要安装Element Plus和axios插件:
```
npm install element-plus axios
```
2. 在Vue项目的main.js文件中引入Element Plus和axios:
```javascript
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import axios from 'axios'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.config.globalProperties.$axios = axios
app.mount('#app')
```
3. 在需要上传附件的组件中,可以使用Element Plus提供的el-upload组件进行上传,同时利用axios发送上传请求:
```vue
<template>
<el-upload
class="upload-demo"
action="/api/upload"
:on-change="handleChange"
:before-upload="beforeUpload"
:file-list="fileList"
multiple
:limit="3"
:on-exceed="handleExceed"
:headers="headers">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: [],
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
}
},
methods: {
handleChange(file, fileList) {
console.log(file, fileList)
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt500K = file.size / 1024 < 500
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
}
if (!isLt500K) {
this.$message.error('上传头像图片大小不能超过 500KB!')
}
return isJPG && isLt500K
},
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${fileList.length + files.length} 个文件`)
},
},
}
</script>
```
4. 在后端接口中,需要处理上传请求,并返回上传成功的信息:
```python
@app.route('/api/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify({'success': True, 'filename': filename})
return jsonify({'success': False})
```
其中,`allowed_file`函数可以用来限制上传文件的格式。
阅读全文
相关推荐


















