There is an api service which can convert audio.wav file to text, and the text string would be returned as a field of json format. I tried to add new feature in a WinFrom program by C# .Net Framework to connect it to the API service to generate text files.
I used swagger and postman to test the API, and both of them successfully returned text generated from the audio file, but my WinFrom App always receives BadRequest 400.
I write a new ConsoleApp project to test the process of uploading a file to API and it also receives BadRequest 400. The errorContent show "TypeError: Cannot read properties of undefined (reading 'filename')n
string url = "api endpoint"; // API endpoint
string filePath = "C:\test.wav"; // The path of audio file
string token = "token"; // The token to access the API endpoint
string requestUri = $"xxx";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var form = new MultipartFormDataContent())
{
byte[] fileBytes = File.ReadAllBytes(filePath);
ByteArrayContent content = new ByteArrayContent(fileBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");
form.Add(content, "audio", Path.GetFileName(filePath));
var response = await client.PostAsync(requestUri, form);
// Handle the response
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Success: " + responseBody);
}
else
{
Console.WriteLine("Error: " + response.StatusCode);
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine("Error Details: " + errorContent);
}
}
}
I tried to find the example code of uploading file by C# and ask ChatGPT to solve it, but I found their code are very similar with mine. The app still receive Bad Request 400 after I modify the code.
2
The error message helps to some extent. It says that the object you’ve sent in the POST request has a property with undefined value.
The name of the property ‘filename’ suggests that that the problematic line is:
form.Add(content, "audio", Path.GetFileName(filePath));
I think so, because, the method which is called, has the following signature according to the Microsoft documentation of the class MultipartFormDataContent
(https://learn.microsoft.com/en-us/dotnet/api/system.net.http.multipartformdatacontent?view=net-8.0):
public void Add (System.Net.Http.HttpContent content, string name, string fileName);
There the third argument is precisely the file name.
This is my hint according to my experience. However I checked what the command Path.GetFileName("C:\test.wav")
produces on my machine and it is not null, but “test.wav” as it should be. Maybe you can also double check what it produces for you just in case, but that is what I can help you with according to your input.
1