Search code examples
pythonflaskwebcam

Capture image from a webcam and upload it to flask server


I have a webpage which can capture images from webcam using webcamjs. I have a flask server on the back end which should accept the image and another form data. I am unable to send the image to Flask server using XMLHttpRequest.

signup.html

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

JavaScript

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) {
        // display results in page
        document.getElementById('results').innerHTML = 
        '<img id="image" src="'+data_uri+'"/>';
      } );      
}

function upload() {
    console.log("Uploading...")
    var image = document.getElementById('image').src;
    var form = document.getElementById('myForm');
    var formData = new FormData(form);
    formData.append("file", image);
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "/signup");
    xmlhttp.send(formData);
    console.log(formData.get('file'));
    console.log(formData.get('userID'));
}

As you can see in the above javascript code I have console.log for 'file' and 'userID'. And this displayed correctly in chrome dev-tools, but the data is not going to flask server. I am not getting any error messages.

Python

@app.route('/signup', methods=['GET','POST'])
def signup():
    if request.method == 'POST':
        return jsonify(request.form['userID'], request.form['file'])
    return render_template('signup.html')

I tried by simply returning return jsonify(request.form['userID']) that didn't working either.

PYTHON DEBUG

127.0.0.1 - - [07/May/2018 17:15:39] "GET /signup HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:39] "GET /static/webcamjs_min.js HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:39] "GET /static/webcam.js HTTP/1.1" 200 -
127.0.0.1 - - [07/May/2018 17:15:57] "POST /signup HTTP/1.1" 200 -

This is Python debug output, as you can see the POST request returned an HTTP response code 200 but there was no output from return statement in python.


Solution

  • Your code is working as expected. The only thing you missed out, is to read a successful POST request in your javascript upload function.

    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) {
            // display results in page
            document.getElementById('results').innerHTML = 
            '<img id="image" src="'+data_uri+'"/>';
          } );      
    }
    
    function upload() {
        console.log("Uploading...")
        var image = document.getElementById('image').src;
        var form = document.getElementById('myForm');
        var formData = new FormData(form);
        formData.append("file", image);
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("POST", "/signup");
    
        // check when state changes, 
        xmlhttp.onreadystatechange = function() {
    
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
            }
        }
    
        xmlhttp.send(formData);
        console.log(formData.get('file'));
        console.log(formData.get('userID'));
    }