Discussions
An error occurs while attempting to upload an image asset to the API endpoint.
3 months ago by Denys
Endpoint: https://upload.heygen.com/v1/asset
Error: {"code":40001,"message":"asset data must be provided"}
try
{
using (var httpClient = new HttpClient())
using (var content = new MultipartFormDataContent())
{
httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
// Determine content type based on fileType
string contentType = "image/jpeg";
// Read file into memory
byte[] fileBytes;
try
{
fileBytes = File.ReadAllBytes(filePath);
Console.WriteLine($"Successfully read {fileBytes.Length} bytes from file.");
}
catch (Exception ex)
{
throw new IOException($"Error reading file: {ex.Message}", ex);
}
// Add file content
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
content.Add(fileContent, "file", Path.GetFileName(filePath));
Console.WriteLine($"File size: {fileBytes.Length} bytes");
// Send request
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await httpClient.PostAsync("https://upload.heygen.com/v1/asset", content);
// Handle response
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response status code: {response.StatusCode}");
Console.WriteLine($"Response body: {responseBody}");
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Failed to upload file. Status Code: {response.StatusCode}, Response: {responseBody}");
}
// Parse response
dynamic responseObject = JsonConvert.DeserializeObject(responseBody);
return responseObject?.id;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error during file upload: {ex.Message}");
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}");
throw;
}