I have the problem that I want to crop an image from a HTML canvas and then send this image from the browser to a REST API that expects an image file in the request body. Since I want to have the frontend app as lightweight as possible, the whole thing is written in Vanilla JS and I prefer to use the fetch API.
I have tested the API endpoint with Insomnia, these are parameters that work (getting 200 and expected response) there: Headers:
Content-Type: application/octet-stream
Prediction-Key: abcsomekey
and as file simply some jpeg
image file.
The catch is that I tried to use the generated JS code which didn't work (getting 400 "BadRequestImageFormat"):
const dataURL = canvasElement.toDataURL()
const base64 = dataURL.split(',')[1]
console.log(base64)
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Prediction-Key': 'abcsomekey'
},
body: base64,
};
fetch('https://some.api.com/some/path', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Also curl didn't work:
curl --request POST \
--url https://some.api.com/some/path \
--header 'Content-Type: application/octet-stream' \
--header 'Prediction-Key: abcsomekey' \
--data 'somebase64string'
How can I solve this? And as a second step, how can I send only part of the canvas (a cropped part of it) instead of the whole thing?