So, I have a simple draw app built on javascript running on python flask. I have a javascript button that outputs a screenshot of what the client drew to the client. Does anyone now how can i output the image back to the server with flask?
Code:
HTML:
<canvas id="canvas"></canvas>
JS:
const canvas = document.getElementById("canvas")
canvas.height = window.innerHeight
canvas.width = window.innerWidth
const ctx = canvas.getContext("2d")
let prevX = null
let prevY = null
ctx.lineWidth = 5
let draw = false
let clearBtn = document.querySelector(".clear")
clearBtn.addEventListener("click", () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
})
let saveBtn = document.querySelector(".save")
saveBtn.addEventListener("click", () => {
let data = canvas.toDataURL("imag/png")
let a = document.createElement("a")
a.href = data
a.download = "sketch.png"
a.click()
})
window.addEventListener("mousedown", (e) => draw = true)
window.addEventListener("mouseup", (e) => draw = false)
window.addEventListener("mousemove", (e) => {
if(prevX == null || prevY == null || !draw){
prevX = e.clientX
prevY = e.clientY
return
}
let currentX = e.clientX
let currentY = e.clientY
ctx.beginPath()
ctx.moveTo(prevX, prevY)
ctx.lineTo(currentX, currentY)
ctx.stroke()
prevX = currentX
prevY = currentY
})
PYTHON:
from flask import Flask, render_template, request
app = Flask(__name__)
dirweb = "templates/"
app = Flask(__name__, template_folder=dirweb)
@app.route("/")
def hello_world():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=False)
Hope someone will know
CodePudding user response:
To send the image data from the client to the server with Flask, you can use an HTTP POST request.
In the JavaScript code, modify the saveBtn
event listener to send an HTTP POST request to the server with the image data as the request body. You can use the fetch function to send the request.
let saveBtn = document.querySelector(".save")
saveBtn.addEventListener("click", () => {
let data = canvas.toDataURL("imag/png")
// Send an HTTP POST request to the server with the image data as the request body
fetch('/save', {
method: 'POST',
body: data
})
.then(response => {
console.log(response)
})
.catch(error => {
console.error(error)
})
})
In the Python code, add a new route to handle the POST request and save the image data to a file on the server.
from flask import Flask, render_template, request
import base64
app = Flask(__name__)
dirweb = "templates/"
app = Flask(__name__, template_folder=dirweb)
@app.route("/")
def hello_world():
return render_template("index.html")
@app.route('/save', methods=['POST'])
def save_image():
# Get the image data from the request body
data = request.data
# Decode the base64 encoded image data
image_data = base64.b64decode(data)
# Save the image data to a file
with open("sketch.png", "wb") as f:
f.write(image_data)
return "Success"
if __name__ == "__main__":
app.run(debug=False)