前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Video File Upload</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<form id="video-upload-form">
<input type="file" id="video-file-input" accept="video/*">
<button type="button" onclick="uploadVideo()">Upload Video</button>
</form>
<script>
async function uploadVideo() {
const inputElement = document.getElementById('video-file-input');
const file = inputElement.files[0];
const formData = new FormData();
formData.append('video_file', file);
try {
const response = await axios.post('服务器IP/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log(response.data);
} catch (error) {
console.error(error.response || error);
}
}
</script>
</body>
</html>
后端python:
import os
from flask import Flask, request, send_from_directory, jsonify
from werkzeug.utils import secure_filename
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
save_path = 'path/to/save/videos'
@app.route('/upload', methods=['POST'])
def upload_file():
# 定义保存文件的位置
if not os.path.exists(save_path):
os.makedirs(save_path)
if 'video_file' not in request.files:
return "No file part", 400
# 接收前端上传的视频文件
video_file = request.files['video_file']
# 检查文件是否有效且为视频类型
if video_file.filename == '' or video_file and not video_file.filename.endswith(
('.mp4', '.avi', '.mov', '.wmv', '.mkv')):
return "Invalid file format", 400
if video_file:
filename = secure_filename(video_file.filename)
file_path = os.path.join(save_path, filename)
# 保存文件到服务器
video_file.save(file_path)
return jsonify(
{
'data': {
'videoUrl': f"服务器IP/videos/{filename}"
},
'code': 200
})
@app.route('/videos/<path:filename>')
def serve_video(filename):
return send_from_directory(save_path, filename, as_attachment=False)
if __name__ == '__main__':
app.run(debug=True)