You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular/TypeScript调用OCR API传图片遇E216错误求助

解决OCR.space API返回E216错误的方案

核心问题分析

E216错误的本质是API无法正确解析传入的图片内容,最常见的原因是Base64字符串带有多余的Data URL前缀,或是请求格式与API要求不匹配。

解决方案

1. 清理Base64字符串的前缀

OCR.space的base64Image参数要求传入纯Base64编码内容,不能包含data:image/xxx;base64,这类前缀。修改scanImage方法,先移除前缀:

scanImage(imageDataUrl: any) {
  if (!imageDataUrl) {
    return throwError(() => new Error('Error: Unable to convert the image.'));
  }
  // 移除Data URL前缀,兼容JPG/PNG格式
  const pureBase64 = imageDataUrl.replace(/^data:image\/(jpeg|jpg|png);base64,/, '');
  
  const data = { 
    base64Image: pureBase64, 
    apikey: environment.ocrApiKey, 
    OCREngine: 2, 
    scale: true, 
    filetype: 'JPG' 
  };

  return fetch(this.apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
    return data;
  })
  .catch((error) => {
    console.error('Error:', error);
    return error;
  });
}

2. 改用FormData上传Blob/File(可选)

如果场景更适合上传Blob或File对象,不要用JSON格式提交,改用multipart/form-data类型的FormData,这能避免文件类型解析问题:

scanImageFile(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('apikey', environment.ocrApiKey);
  formData.append('OCREngine', '2');
  formData.append('scale', 'true');

  return fetch(this.apiUrl, {
    method: 'POST',
    body: formData, // 无需手动设置Content-Type,浏览器会自动处理
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
    return data;
  })
  .catch((error) => {
    console.error('Error:', error);
    return error;
  });
}

额外排查点

  • 确认filetype参数值与实际图片格式一致(比如图片是PNG就传PNG,不要传JPG)
  • 检查API密钥是否正确,且未超出免费额度
  • 确保图片内容无损坏,Base64编码完整

内容的提问来源于stack exchange,提问作者Florian A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:42:42