如何在JavaScript中发布帆布数据?

发布于 2025-01-30 10:38:02 字数 755 浏览 3 评论 0原文

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安静 2025-02-06 10:38:02

Matslindh的方式是正确的,但是您可以通过FormData尝试上传图像,因此您没有转换为base64,然后转换回图像

const dataURItoBlob = function(dataURI : string) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString : string;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
const url = canvas.toDataURL()
const file = dataURItoBlob(url)

//add file to formdata

const form = new FormData()
form.append('file', item.file)
//post this form in body

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

const dataURItoBlob = function(dataURI : string) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString : string;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
const url = canvas.toDataURL()
const file = dataURItoBlob(url)

//add file to formdata

const form = new FormData()
form.append('file', item.file)
//post this form in body
慈悲佛祖 2025-02-06 10:38:02

uploadfile期望将文件发布到multipart/form -data格式中的端点 - IE作为常规帖子,并带有一些添加的元数据。

由于您正在检索图像数据并将其提交为JSON主体,因此与预期格式不符。您也想使用canvas.todataurl() >在尝试通过API提交以避免JSON的任何UTF-8问题之前,将内容转换为base64

const pngData = canvas.toDataURL();

// then in your request:
body: JSON.stringify({
  input_data: pngData,
}),

要处理此请求,请更改您的视图函数签名以接收input_data parameter(并使用比post的更好端点名称:

@app.post("/images")
async def upload_files(input_data: str = Body(...)):
     # check the expected format (content-type;<base64 content>)
     # .. and decode it with base64.b64decode()
     return {'content': input_data}

UploadFile expects a file being posted to the endpoint in the multipart/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.

const pngData = canvas.toDataURL();

// then in your request:
body: JSON.stringify({
  input_data: pngData,
}),

To handle this request change your view function signature to receive an input_data parameter (and use a better endpoint name than post):

@app.post("/images")
async def upload_files(input_data: str = Body(...)):
     # check the expected format (content-type;<base64 content>)
     # .. and decode it with base64.b64decode()
     return {'content': input_data}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文