You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask实现摄像头捕获图片后跳转页面显示文件名问题

问题修复:摄像头截图上传后跳转页面并显示文件名

问题根源

  1. 现有代码用XMLHttpRequest发送请求,但未处理响应结果,点击上传后无页面跳转动作
  2. 上传的是图片的data URI字符串,不是标准文件对象,后端无法获取有效文件名
  3. 后端错误地从request.form['file']取值,文件上传需通过request.files处理

修复方案

1. 前端调整

  • 将data URI格式的图片转换为Blob对象,再封装成File对象添加到FormData,自定义文件名
  • 在请求完成后,根据后端响应跳转至Test2页面

2. 后端调整

  • 从request.files获取上传文件,提取文件名
  • 通过重定向传递文件名参数到Test2页面,再渲染展示

修改后的代码

app.py

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/Test', methods=['GET','POST'])
def Test():
    if request.method == 'POST':
        uploaded_file = request.files.get('file')
        if uploaded_file:
            filename = uploaded_file.filename
            # 可选:添加文件保存逻辑,比如 uploaded_file.save(f'uploads/{filename}')
            return redirect(url_for('test2', filename=filename))
        return render_template('Test.html')
    return render_template('Test.html')

@app.route('/Test2')
def test2():
    filename = request.args.get('filename', '无文件名')
    return render_template('Test2.html', data=filename)

if __name__ == '__main__':
    app.run(debug=True)

Test.html

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>WebcamJS Test Page</title>
    <style type="text/css">
        body { font-family: Helvetica, sans-serif; }
        h2, h3 { margin-top:0; }
        form { margin-top: 15px; }
        form > input { margin-right: 15px; }
        #results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
    </style>
</head>
<body>
    <div id="results">Your captured image will appear here...</div>
    
    <h1>WebcamJS Test Page</h1>
    <h3>Demonstrates simple 320x240 capture & display</h3>
    
    <div id="my_camera"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.min.js" integrity="sha512-dQIiHSl2hr3NWKKLycPndtpbh5iaHLo6MwrXm7F0FM5e+kL2U16oE9uIwPHUl6fQBeCthiEuV/rzP3MiAB8Vfw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>   
    <form method="POST" enctype="multipart/form-data" id="myForm">
        <table>
            <tr>
                <td>Name/EmailId</td>
                <td>:  <input type="text" name="userID"></td>
            </tr>
            <tr>
                <td><input type="button" value="Upload" onclick="upload()"></td>
            </tr>
        </table>
    </form>
    <div id="my_camera"></div>
    <input type="button" onclick="snap()" value="Snap">
    <div id="results"></div>
    
    </body>
<script>
function ShowCam() {
    Webcam.set({
        width: 320,
        height: 240,
        image_format: 'jpeg',
        jpeg_quality: 100
    });
    Webcam.attach('#my_camera');
}
window.onload= ShowCam;

function snap() {
    Webcam.snap( function(data_uri) {
        document.getElementById('results').innerHTML = 
        '<img id="image" src="'+data_uri+'"/>';
      } );      
}

function upload() {
    console.log("Uploading...")
    var imageSrc = document.getElementById('image').src;
    var form = document.getElementById('myForm');
    var formData = new FormData(form);

    // 将data URI转换为Blob
    function dataURItoBlob(dataURI) {
        var byteString = atob(dataURI.split(',')[1]);
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ab], {type: mimeString});
    }

    var blob = dataURItoBlob(imageSrc);
    var file = new File([blob], 'captured_image.jpg', {type: 'image/jpeg'});
    formData.append("file", file);

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "/Test");

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            window.location.href = this.responseURL;
        }
    }

    xmlhttp.send(formData);
}
</script>
</html>

Test2.html

<!DOCTYPE html>
<html>
<body>
    <h1>上传成功</h1>
    <p>您上传的图片文件名:{{data}}</p>
</body>
</html>

内容的提问来源于stack exchange,提问作者Usman Rafiq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:54:11