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

使用Aspose.OMR API识别模板遇415错误,求解决方案

Aspose.OMR API识别失败:415 Unsupported Media Type错误

调用Aspose.OMR的/v5.1/omr/RecognizeTemplate/PostRecognizeTemplate接口时,传入Base64格式的OMR模板和答题卡图片,收到415「Unsupported Media Type」错误。

我的C#代码:

public async Task<string> RecognizeTemplateAsync(string accessToken, string filledTemplateImageBase64, string omrFileBase64, string outputFormat, int recognitionThreshold)
{
    // Create the multipart form data content
    var formData = new MultipartFormDataContent();

    // Add the filled template image (Base64-encoded)
    var imageContent = new StringContent(filledTemplateImageBase64, Encoding.UTF8, "text/plain");
    formData.Add(imageContent, "Images");

    // Add the OMR template file (Base64-encoded)
    var omrFileContent = new StringContent(omrFileBase64, Encoding.UTF8, "text/plain");
    formData.Add(omrFileContent, "omrFile");

    // Add other parameters
    formData.Add(new StringContent(outputFormat, Encoding.UTF8), "outputFormat");
    formData.Add(new StringContent(recognitionThreshold.ToString(), Encoding.UTF8), "recognitionThreshold");

    // Set headers
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    // Send request
    var response = await _httpClient.PostAsync("https://api.aspose.cloud/v5.1/omr/RecognizeTemplate/PostRecognizeTemplate", formData);

    // Check for errors
    if (!response.IsSuccessStatusCode)
    {
        var errorResponse = await response.Content.ReadAsStringAsync();
        throw new HttpRequestException($"Error recognizing template: {response.StatusCode}. Response: {errorResponse}");
    }

    // Read the response as JSON
    var responseData = await response.Content.ReadAsStringAsync();
    return responseData;
}


[HttpPost("RecognizeTemplate")]
public async Task<IActionResult> RecognizeTemplate(
    [FromForm] string Images, // List of Base64-encoded images
    [FromForm] string omrFile, // Base64-encoded OMR template file
    [FromForm] string outputFormat, // Output format (e.g., "CSV")
    [FromForm] int recognitionThreshold) // Recognition threshold (e.g., 35)
{
    try
    {
        // Step 1: Validate inputs
        if (Images == null)
        {
            return BadRequest("At least one filled template image is required.");
        }

        if (string.IsNullOrEmpty(omrFile))
        {
            return BadRequest("OMR template file is required.");
        }

        if (string.IsNullOrEmpty(outputFormat))
        {
            return BadRequest("Output format is required.");
        }

        // Step 2: Get Access Token
        var clientId = "";
        var clientSecret = "";
        var accessToken = await _accessTokenService.GetAccessTokenAsync(clientId, clientSecret);

        // Step 3: Recognize the filled template
        var recognitionResult = await _omrService.RecognizeTemplateAsync(
            accessToken,
            Images,
            omrFile,
            outputFormat,
            recognitionThreshold);

        // Step 4: Return the recognition result
        return Content(recognitionResult, "application/json");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Error recognizing template: {ex.Message}");
    }
}

错误响应:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
  "title": "Unsupported Media Type",
  "status": 415,
  "traceId": "00-3416c993f09f7b5a4f53408ef0b8888e-a23775435dd324eb-00"
}

解决方案

415错误的核心原因是接口要求上传二进制文件,而非Base64字符串。Aspose.OMR的PostRecognizeTemplate接口需要通过multipart/form-data上传实际的图片文件(如PNG/JPG)和OMR模板文件(.omr格式),而不是Base64编码的字符串。

修改步骤:

  • 将Base64字符串转换为二进制字节流,作为文件内容上传
  • 为文件内容设置匹配实际类型的Content-Type(图片用image/png/image/jpeg,OMR模板用application/octet-stream)

修改后的代码:

public async Task<string> RecognizeTemplateAsync(string accessToken, string filledTemplateImageBase64, string omrFileBase64, string outputFormat, int recognitionThreshold)
{
    var formData = new MultipartFormDataContent();

    // 移除Base64前缀(如果有的话),转换为字节流后添加为图片文件
    var cleanImageBase64 = filledTemplateImageBase64.Replace("data:image/png;base64,", "").Replace("data:image/jpeg;base64,", "");
    var imageBytes = Convert.FromBase64String(cleanImageBase64);
    var imageContent = new ByteArrayContent(imageBytes);
    imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/png"); // 根据实际图片格式调整
    formData.Add(imageContent, "Images", "filled_template.png"); // 文件名可自定义

    // 转换OMR模板Base64为字节流,添加为文件
    var omrBytes = Convert.FromBase64String(omrFileBase64);
    var omrContent = new ByteArrayContent(omrBytes);
    omrContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    formData.Add(omrContent, "omrFile", "template.omr"); // 文件名可自定义

    // 添加其他参数
    formData.Add(new StringContent(outputFormat, Encoding.UTF8), "outputFormat");
    formData.Add(new StringContent(recognitionThreshold.ToString(), Encoding.UTF8), "recognitionThreshold");

    // 设置授权头
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    // 发送请求
    var response = await _httpClient.PostAsync("https://api.aspose.cloud/v5.1/omr/RecognizeTemplate/PostRecognizeTemplate", formData);

    if (!response.IsSuccessStatusCode)
    {
        var errorResponse = await response.Content.ReadAsStringAsync();
        throw new HttpRequestException($"识别失败: {response.StatusCode}. 响应内容: {errorResponse}");
    }

    return await response.Content.ReadAsStringAsync();
}

额外注意事项:

  • 若需上传多张图片,重复添加Images字段即可(接口支持多文件上传)
  • 确保Base64字符串无多余前缀,若存在需先截取
  • 验证OMR模板为Aspose.OMR生成的有效.omr文件

内容的提问来源于stack exchange,提问作者Mzfr Rgab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 23:14:52