0

I am trying to upload an image to the Microsoft custom vision API prediction endpoint using Restsharp, I am trying to use the AddFile method but I am getting a BadRequest as the result, here is the code I am using

public IRestResponse<PredictionResponse> Predict(string imageFileName)
    {
        var file = new FileInfo(imageFileName);
        var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
        var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
        var client = new RestClient(serviceUrl);
        var request = new RestRequest(Method.POST);
        request.AddHeader("Content-Type", "application/octet-stream");
        request.AddHeader("Prediction-Key", serviceKey);
        request.AddFile(file.Name, file.FullName);
        var response = client.Execute<PredictionResponse>(request);
        return response;
    }

When I execute the method I am getting the following response back from the service

{
  "code": "BadRequestImageFormat",
  "message": "Bad Request Image Format, Uri: 1062fe0480714281abe2daf17beb3ac5"
}
Oscar Marin
  • 136
  • 2
  • 8

1 Answers1

1

After looking for ways in the restsharp documentation to properly upload a file, I came to the solution that it needs to be passed as parameter with an array of bytes with the parameter type of ParameterType.RequestBody

Here is the example of the method that actually works

public IRestResponse<PredictionResponse> Predict(string imageFileName)
        {
            var file = new FileInfo(imageFileName);
            var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
            var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
            var client = new RestClient(serviceUrl);
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/octet-stream");
            request.AddHeader("Prediction-Key", serviceKey);
            request.AddParameter("content", File.ReadAllBytes(file.FullName), ParameterType.RequestBody);
            var response = client.Execute<PredictionResponse>(request);
            return response;
        }
Oscar Marin
  • 136
  • 2
  • 8