I’m trying to upload a file using a HTTPClient but getting the error “Unsupported Media Type”. In the logging of Hubspot I don’t even see the request so I can’t get more logging about the request. I’ve tried the old and new api url but without luck. Anyone got some example C# code to upload a file?
Can you share the headers of the request you are making, specifically the “Content-Type”. This should be set to “multipart/form-data” otherwise you’ll get the error you are seeing. This is some sample code that works to upload a file using C#:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.hubapi.com/files/v3/files");
request.Headers.Add("Authorization", "Bearer INSERT_YOUR_ACCESS_TOKEN");
var content = new MultipartFormDataContent();
content.Add(new StreamContent(File.OpenRead("INSERT_PATH_TO_FILE")), "file", "INSERT_PATH_TO_FILE");
content.Add(new StringContent("{\"access\": \"PUBLIC_NOT_INDEXABLE\"}"), "options");
content.Add(new StringContent("INSERT_HUBSPOT_FOLDER_ID"), "folderId");
content.Add(new StringContent("INSERT_FILE_NAME"), "fileName");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
Thank you, I had to change using the class MultipartForm to MultipartFormDataContent. Maybe nice for other people my function:
private Task<HttpResponseMessage> UploadFile(byte[] file)
{
var fileContent = new ByteArrayContent(file);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "test.docx"
};
var accessDictionary = new Dictionary<string, string>
{
{ "access", "PUBLIC_INDEXABLE" }
};
string accessJson = JsonConvert.SerializeObject(accessDictionary);
var accessContent = new StringContent(accessJson);
accessContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
accessContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "options"
};
var folderContent = new StringContent("/");
folderContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "folderPath"
};
var requestContent = new MultipartFormDataContent
{
fileContent,
accessContent,
folderContent
};
return _hubSpotClient.PostAsync(_hubSpotSettings.FilesRelativeUrl, requestContent);
}