用python代码写一个 flask_uploads插件上传图片和视频的代码
时间: 2024-05-14 09:16:49 浏览: 82
Sure, 下面是 Flask-Uploads 插件实现图片和视频上传的 Python 代码:
``` python
from flask import Flask, request
from flask_uploads import UploadSet, configure_uploads, IMAGES, VIDEOS
app = Flask(__name__)
photos = UploadSet('photos', IMAGES)
videos = UploadSet('videos', VIDEOS)
app.config['UPLOADED_PHOTOS_DEST'] = 'uploads/photos'
app.config['UPLOADED_VIDEOS_DEST'] = 'uploads/videos'
configure_uploads(app, (photos, videos))
@app.route('/upload', methods=['POST'])
def upload():
photo_filename = ''
video_filename = ''
if 'photo' in request.files:
photo = request.files['photo']
photo_filename = photos.save(photo)
if 'video' in request.files:
video = request.files['video']
video_filename = videos.save(video)
return f"Photo file: {photo_filename} Video file: {video_filename}"
if __name__ == '__main__':
app.run()
```
这段代码定义了两个 UploadSet,即 photos 和 videos,分别用于保存图片和视频。然后在 Flask 的配置中设置上传文件的保存目录,并将两个 UploadSet 配置到应用中。接着,定义了一个路由 `/upload`,当收到 POST 请求时,从请求的文件中获取图片和视频,如果存在则保存到指定的目录,并返回保存的文件名。
阅读全文