前端上传视频后端python接收并返回视频链接

前端代码:

<!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)

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值