vue3 flask上传保存文件
时间: 2023-08-27 07:05:08 浏览: 46
前端使用Vue3,后端使用Flask,实现文件上传并保存的步骤如下:
前端:
1. 在Vue组件中,添加一个input标签,type为file,用于选择文件:
```html
<template>
<div>
<input type="file" @change="handleFileChange">
</div>
</template>
```
2. 在methods中定义handleFileChange方法,获取用户选择的文件:
```javascript
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
}
}
```
3. 在methods中定义uploadFile方法,使用axios将文件发送到后端:
```javascript
methods: {
uploadFile() {
const formData = new FormData();
formData.append('file', this.file);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
}
}
```
后端:
1. 在Flask中定义/upload路由,用于接收文件:
```python
from flask import Flask, request
import os
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File uploaded successfully!'
```
2. 在Flask中定义UPLOAD_FOLDER常量,用于指定文件保存路径:
```python
app.config['UPLOAD_FOLDER'] = 'path/to/save/files'
```
注意:需要确保path/to/save/files路径存在,并且具有写入权限。
这样就完成了前后端文件上传保存的流程。