2017-08-03 73 views
0

我想使用API​​上傳訓練圖像。 https://southcentralus.dev.cognitive.microsoft.com/docs/services/d9a10a4a5f8549599f1ecafc435119fa/operations/58d5835bc8cb231380095be3MS認知服務CreateImagesFromData UnknownMediaType

這是我的代碼。

public async Task<CreateImageResult> CreateImagesFromData(byte[] _image) 
{ 
    using (var client = new HttpClient()) 
    { 
     client.BaseAddress = new Uri(_baseAddress); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     client.DefaultRequestHeaders.Add("Training-key", _trainingKey); 

     HttpResponseMessage response; 

     using (var content = new ByteArrayContent(_image)) 
     { 
      response = await client.PostAsync(String.Format("Training/projects/{0}/images/image?tagIds=Default", _projectId), content); 
     } 

     HttpContent data = response.Content; 
     string result = await data.ReadAsStringAsync(); 
     return JsonConvert.DeserializeObject<CreateImageResult>(result); 
    } 
} 

這個請求會拋出一個UnkonwnMediaType,我想知道我錯過了什麼。

_image參數是有效的image/jpeg字節數組。

回答

1

我自己找到了答案。

public async Task<CreateImageResult> CreateImagesFromData(byte[] _image) 
{ 
    HttpContent bytesContent = new ByteArrayContent(_image); 

    using (var client = new HttpClient()) 
    { 
     client.BaseAddress = new Uri(_baseAddress); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     client.DefaultRequestHeaders.Add("Training-key", _trainingKey); 

     HttpResponseMessage response; 

     using (var content = new MultipartFormDataContent()) 
     { 
      content.Add(bytesContent, "Image", "Image"); 
      response = await client.PostAsync(String.Format("Training/projects/{0}/images/image?tagIds=Default", _projectId), content); 
     } 

     HttpContent data = response.Content; 
     string result = await data.ReadAsStringAsync(); 
     return JsonConvert.DeserializeObject<CreateImageResult>(result); 
    } 
}