upload a file to a course by API

SanazPejman
Community Member

Hello , my code in c# for upload afile in a course is :

public async Task<Canvas_File> UploadFileToCanvasAsync(string courseId, string filePath, string parentFolderPath)
{
// Step 1: Notify Canvas about the file upload
var localToken = _options.LocalToken;
var notifyResponse = await NotifyCanvasAboutFileUploadAsync(courseId, filePath, parentFolderPath, localToken);
string uploadUrl = notifyResponse.upload_url;
var uploadParams = ((JObject)notifyResponse.upload_params).ToObject<Dictionary<string, string>>();
 
// Step 2: Upload the file to the given URL
string locationUrl = await UploadFileDataAsync(uploadUrl, uploadParams, filePath);
 
// Step 3: Confirm the upload
var canvasFile = await ConfirmFileUploadAsync(locationUrl, localToken);
 
return canvasFile;
}
 
private async Task<dynamic> NotifyCanvasAboutFileUploadAsync(string courseId, string filePath, string parentFolderPath, string token)
{
var fileInfo = new FileInfo(filePath);
var mimeType = "image/png";
 
var requestUri = $"/api/v1/courses/{courseId}/files";
 
var formData = new MultipartFormDataContent
{
{ new StringContent(fileInfo.Name), "name" },
{ new StringContent(fileInfo.Length.ToString()), "size" },
{ new StringContent(mimeType), "content_type" },
{ new StringContent(parentFolderPath), "parent_folder_path" }
};
 
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
 
var response = await _httpClient.PostAsync(requestUri, formData);
response.EnsureSuccessStatusCode();
 
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<dynamic>(jsonResponse);
}
 
private async Task<string> UploadFileDataAsync(string uploadUrl, IDictionary<string, string> uploadParams, string filePath)
{
using (var formContent = new MultipartFormDataContent())
{
foreach (var param in uploadParams)
{
formContent.Add(new StringContent(param.Value), param.Key);
}
 
var fileInfo = new FileInfo(filePath);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
formContent.Add(streamContent, "file", fileInfo.Name);
 
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(uploadUrl, formContent);
response.EnsureSuccessStatusCode();
 
// The redirect URL should be in the Location header
return response.RequestMessage?.RequestUri?.ToString() ?? "";
}
}
}
 
private async Task<Canvas_File> ConfirmFileUploadAsync(string location, string token)
{
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, location);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(""); 
 
 
var response = await httpClient.SendAsync(request);
 
if (!response.IsSuccessStatusCode)
{
// Handle the error appropriately
throw new HttpRequestException($"Request failed with status code {response.StatusCode}");
}
 
var jsonResponse = await response.Content.ReadAsStringAsync();
var canvasFile = JsonConvert.DeserializeObject<Canvas_File>(jsonResponse);
return canvasFile;
}
}
 
Step 1 (NotifyCanvasAboutFileUploadAsync) and step 2 (UploadFileDataAsync) works correctly by success code. But in level 3 (ConfirmFileUploadAsync) is failed by 400 error. my token and location='' http://domain/api/v1/files/67/create_success?uuid=dFFo326beHGE4BKWrnTnZlP0yJZoZPcMereadQ7k" set correctly! how can I fix this?
0 Likes