需求说明
技术栈:
前端采用原生HTML+JavaScript
后端采用Flask框架
操作步骤:
完整代码如下:
有关FormData的使用参考:FormData 对象的使用 - Web API 接口参考 | MDN
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>视频上传title>
- head>
-
- <body>
- <input type="file" id="video" accept="video/mp4">
- <button onclick="upload()">上传视频button>
-
- <script>
- function upload() {
- let videoUpload = document.getElementById('video')
- let video = videoUpload.files[0]
-
- let formData = new FormData()
- formData.append('video', file) //文件
- formData.append('name', file.name) //文件名
-
- let xhr = new XMLHttpRequest()
- xhr.open('POST', 'http://10.241.4.160:5000/upload', true)
- xhr.responseType = 'text' //响应类型
- xhr.onload = function () {
- if (xhr.status === 200) {
- console.log(xhr.response); //响应内容 (上传成功/文件已存在)
- } else {
- console.error('请求失败,状态码:' + xhr.status);
- }
- };
- xhr.send(formData)
- }
- script>
- body>
- html>
操作步骤:
完整代码如下:
- from flask import Flask, request, jsonify
- from flask_cors import CORS
-
- app = Flask(__name__)
- CORS(app, supports_credentials=True) #允许所有来源的跨域请求
-
- # 文件上传
- @app.route('/upload', methods=["POST"])
- def upload():
- file = request.files['file'].stream.read() #视频文件
- name = request.form['name'] #文件名(注意是表单格式)
- print(video_exist(name))
- if not video_exist(name):
- # 保存视频文件到本地
- file_path = os.getcwd() + '\\videos\\' + name
- with open(file_path,'ab') as f:
- f.write(file)
- return '上传成功'
- else:
- return '文件已经存在'
-
- # 判断文件是否存在
- def video_exist(video_name):
- path = os.getcwd() + '\\videos\\'
- video_path = os.path.join(path,video_name)
- return os.path.isfile(video_path)
-
- if __name__ == '__main__':
- app.run()
后续的视频处理可以考虑使用cv2来进行,例如通过cv2.VideoCapture(path)方法来读取指定路径的视频文件