Hi,
I try to upload xls file using c# and I am facing “Bad Request” error. Shared you with my code
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Program
{
static async Task Main(string[] args)
{
// Replace with your KoboToolbox details
string apiToken = "**************************************************************"; // Your KoboToolbox API token
string assetUid = "************************************"; // The project's UID
string mediaFilePath = @"D:\rk\Testing\KoboTesting.xls"; // Path to the file to upload
File.WriteAllText(mediaFilePath, "File Upload");
// API v3 Endpoint
string uploadUrl = $"https://kf.kobotoolbox.org/api/v2/assets/{assetUid}/files/";
//string uploadUrl = @"https://kc.kobotoolbox.org/api/v1/forms/{assetUid}/media";
using (HttpClient client = new HttpClient())
{
// Set Authorization header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", apiToken);
// Prepare the file content
using (MultipartFormDataContent formData = new MultipartFormDataContent())
{
// Add the media file to the form data
var fileContent = new StreamContent(File.OpenRead(mediaFilePath));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
formData.Add(fileContent, "file", Path.GetFileName(mediaFilePath));
try
{
// Send POST request to upload the file
HttpResponseMessage response = await client.PostAsync(uploadUrl, formData);
// Check the response
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Media file uploaded successfully!");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response: " + responseBody);
}
else
{
Console.WriteLine($"Failed to upload media file. Status Code: {response.StatusCode}");
string errorResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine("Error Response: " + errorResponse);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
}
}
Output Error::