Flask mp4文件未使用文件路径显示在视频标签中

2024-04-26 23:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个flask应用程序,它将mp4文件存储在本地目录中,并将路径保存在我的数据库中。我能够访问flask和download提供的文件usersend_file,但是当我传递到视频标签的路径时,它不会显示。见下面的代码:

保存视频文件:works fine as expected

@app.route('/', methods=['GET', 'POST'])
def index():
      form = VideoPicForm()
      if form.validate_on_submit():
        if form.vid.name not in request.files:
            flash('No video part specified')
            return redirect(url_for('index'))
        file = request.files[form.vid.name]
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(url_for('index'))
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filepath = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)
            file.save(filepath)
            video= VideosFiles(description=form.description.data, vidpath=filepath)
            db.session.add(video)
            db.session.commit()
            flash('video uploaded successfully...')
            return redirect(url_for('index'))
return render_template('index.html', title='Home', form=form)

从模板访问:``文件未呈现`

@app.route('/display')
def display():
    file_data= VideosFiles.query.filter_by(id=1).first()
    video= file_data.vidpath
    return render_template('display.html', title='Videos', video=video)

在模板中:

<video width="320" height="240" controls>
    <source src="{{video}}" type="video/mp4" />
</video>

但当我使用send_file下载时,视频会立即下载:

@app.route('/download')
def download():
    file_data= VideosFiles.query.filter_by(id=1).first()
    video= file_data.vidpath
    return send_file(video, as_attachment=True)

我遗漏了导致视频无法在模板中呈现的任何内容


Tags: 文件formappfordataindex视频return
1条回答
网友
1楼 · 发布于 2024-04-26 23:22:46

您的代码中有一个小改动。确保您的视频存储在flask应用程序结构的静态文件夹中

我和你有同样的问题,当我将视频存储在静态文件夹中时,它工作正常

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
<video width="400" controls>
<source src="{{ url_for('static', filename='small.mp4') }}" type="video/mp4">
</video>
</body>
</html>

也请使用url_进行html呈现

相关问题 更多 >