I’m trying to pull image from client(javascript) to sever(flask) but i got error while doing that. Even i tried to set ‘Content-Type’: ‘application/json’ but when i return the ‘content_type’ it gave me ‘application/x-www-form-urlencoded’. Please help me.
This is my app.py
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/save-image', methods=['POST'])
def save_image():
content_type = request.headers.get('Content-Type')
if (content_type != 'application/json'):
return content_type
# This return application/x-www-form-urlencoded
data = request.get_json()
if not data or not data.get('imageData'):
return 'Missing image data'
image_data = data['imageData']
image_data = image_data.split(',')[1]
image_data = base64.b64decode(image_data)
filename = f'{uuid.uuid4()}.png'
filepath = os.path.join('images', filename)
This is my JavaScript
<button id="snap">Take Photo</button>
<form method="POST" action="/save-image">
<video id="video" width="600" height="440" autoplay style="background-color: grey"></video>
<canvas name="image" id="canvas" width="600" height="440" style="background-color: grey"></canvas>
<button onclick="sendCanvasImage()">Convert to Image</button>
</form>
<script>
// Elements for taking the snapshot
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function(stream) {
video.srcObject = stream;
video.play();
});
}
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 600, 400);
});
async function sendCanvasImage() {
var canvas = document.getElementById('canvas');
var imageData = canvas.toDataURL('image/png'); // Specify image format (optional)
var response = await fetch('/save-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // Set content type
},
body: JSON.stringify({ imageData }) // Send data in JSON format
});
}
</script>