用flask实现elmentui上传图片
时间: 2023-11-28 19:05:25 浏览: 67
以下是一个使用Flask和ElementUI实现上传图片的示例代码:
Python代码
```python
from flask import Flask, request, jsonify
import os
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = file.filename
file.save(os.path.join('uploads', filename))
return jsonify({'message': 'success', 'filename': filename})
if __name__ == '__main__':
app.run(debug=True)
```
HTML代码
```html
<el-upload
class="upload-demo"
action="/upload"
:on-success="handleSuccess"
:data="{_token: 'your_csrf_token'}"
name="file"
:show-file-list="false">
<el-button size="small" type="primary">上传图片</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
```
在上面的代码中,我们首先定义了一个Flask应用程序,并在其中定义了一个`/upload`路由,该路由将处理上传文件的POST请求。路由函数首先从请求中获取上传的文件,然后将其保存到`uploads`目录中,并返回一个JSON响应,其中包含上传文件的文件名。
在HTML代码中,我们使用了ElementUI的`el-upload`组件来处理文件上传。我们指定了上传的URL和一些其他选项,例如上传成功后的回调函数和要上传的文件类型。我们还为文件上传设置了一个CSRF令牌,以防止跨站请求伪造攻击。
请注意,上面的代码只适用于小型文件的上传。对于大型文件的上传,您应该使用其他库,例如Flask-Uploads或Flask-Dropzone。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)