如何在JavaScript中发布帆布数据?
我使用JavaScript和FastApi构建了一个简单的项目。我想将Canvas图像数据在JavaScript中发布到服务器(FastAPI)。
但是,我得到422个无法处理的实体错误,
# FastAPI
@app.post("/post")
async def upload_files(input_data: UploadFile = File(...)):
return JSONResponse(status_code = 200, content={'result' : 'success'})
// javascript
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
imageData = ctx.getImageData(0, 0, 112, 112);
fetch("http://{IP}/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input_data: imageData,
}),
})
.then((response) => response.json())
这是我的代码。我是JavaScript的新手。因此,我不知道如何将数据发布到服务器。 我该怎么办?提前致谢。
I built a simple project using javascript and FastAPI. I would like to POST canvas image data in javascript to the server(FastAPI).
But, I get the 422 Unprocessable Entity error
# FastAPI
@app.post("/post")
async def upload_files(input_data: UploadFile = File(...)):
return JSONResponse(status_code = 200, content={'result' : 'success'})
// javascript
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
imageData = ctx.getImageData(0, 0, 112, 112);
fetch("http://{IP}/post", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input_data: imageData,
}),
})
.then((response) => response.json())
here is my code. I am new one in javascript. so I don't know how can post data to server.
How can I do? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Matslindh的方式是正确的,但是您可以通过FormData尝试上传图像,因此您没有转换为base64,然后转换回图像
MatsLindh's way is correct but you can try upload image by formdata so you haven't convert to base64 then convert back to image
uploadfile
期望将文件发布到multipart/form -data
格式中的端点 - IE作为常规帖子,并带有一些添加的元数据。由于您正在检索图像数据并将其提交为JSON主体,因此与预期格式不符。您也想使用
canvas.todataurl() >在尝试通过API提交以避免JSON的任何UTF-8问题之前,将内容转换为base64
。
要处理此请求,请更改您的视图函数签名以接收
input_data
parameter(并使用比post
的更好端点名称:UploadFile
expects a file being posted to the endpoint in themultipart/form-data
format - i.e. as a regular POST with a bit of added metadata.Since you're retrieving the image data and submitting it as JSON body, that won't match the expected format. You also want to use
canvas.toDataURL()
to convert the content to base64 before trying to submit it through your API to avoid any UTF-8 issues with JSON.To handle this request change your view function signature to receive an
input_data
parameter (and use a better endpoint name thanpost
):