繁体   English   中英

使用 fetch 以图像文件作为正文的 POST 请求 API

[英]POST request with image file as body using fetch API

我有一个问题,我想从 HTML canvas 裁剪图像,然后将此图像从浏览器发送到 REST API,它期望请求正文中有图像文件。 因为我想让前端应用程序尽可能轻量,所以整个东西都是用 Vanilla JS 编写的,我更喜欢使用 fetch API。

我已经用 Insomnia 测试了 API 端点,这些是在那里工作的参数(获得 200 和预期的响应):标题:

Content-Type: application/octet-stream
Prediction-Key: abcsomekey

作为文件只是一些jpeg图像文件。

问题是我试图使用生成的 JS 代码,但它不起作用(得到 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));

curl 也不起作用:

curl --request POST \
  --url https://some.api.com/some/path \
  --header 'Content-Type: application/octet-stream' \
  --header 'Prediction-Key: abcsomekey' \
  --data 'somebase64string'

我该如何解决这个问题? 作为第二步,我怎样才能只发送 canvas 的一部分(其中的一部分)而不是全部?

如果正文是ArrayBuffer ,它可以作为原始 HTTP POST 正文发布。

使用您的代码和 canvasElement,它看起来像这样:

const context = canvasElement.getContext("2d");
const imageData = context.getImageData(x, y, w, h);
const buffer = imageData.data.buffer; // this is an ArrayBuffer

const options = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/octet-stream',
        'Prediction-Key': 'abcsomekey'
    },
    body: buffer,
};
    
fetch('https://some.api.com/some/path', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM