How to retrieve the content of a IFormFile when uploading to onedrive's user using microsoft api

29 views Asked by At

I do have some problems when uploading files with Batch Request of Microsoft graph API. My file and folder will upload but when i try to open the file, i have an error and i can't see the content of this file. Here what I did so far :

        public async Task BatchUploadFileAsync(string DriveID, GetAllFilesToUpload filesToUpload)
        {

            int batchSize = 20;

            var batchesOfFiles = new List<List<FileDatatoUpload>>();
            var currentBatch = new List<FileDatatoUpload>();

            foreach (var file in filesToUpload.Files)
            {
                currentBatch.Add(new FileDatatoUpload
                {
                    FormFile = file.FormFile,
                    Folder = file.Folder,
                    TypeOfDocument = file.TypeOfDocument,
                    SchoolYear = file.SchoolYear,
                    Curriculum = file.Curriculum,
                    Language = file.Language,
                    Semestre = file.Semestre,
                    PathStudent = file.PathStudent,
                    AcademicYear = file.AcademicYear,
                    Student = file.Student
                });

                if (currentBatch.Count == batchSize)
                {
                    batchesOfFiles.Add(currentBatch);
                    currentBatch = new List<FileDatatoUpload>();
                }
            }

            if (currentBatch.Count > 0)
            {
                batchesOfFiles.Add(currentBatch);
                currentBatch = new List<FileDatatoUpload>();
            }

            var batchRequestContent = new BatchRequestContent();

            try
            {

                // Parcourez chaque lot de fichiers
                foreach (var batchFiles in batchesOfFiles)
                {
                    foreach(var file in batchFiles)
                    {
                        // Lecture du contenu du fichier
                        using (var fileStream = file.FormFile.OpenReadStream())
                        {

                            byte[] fileBytes = new byte[fileStream.Length];
                            fileStream.Read(fileBytes, 0, fileBytes.Length);

                            string fileBase64 = Convert.ToBase64String(fileBytes);
                            var jsonObject = new
                            {
                                contentBytes = fileBase64
                            };

                            // Sérialisation en JSON
                            string jsonContent = JsonConvert.SerializeObject(jsonObject);

                            // Création de StringContent à partir du JSON
                            var stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                            // Création de la requête de chargement
                            var request = _graphServiceClientApp.Users["userId"].Drive.Root
                                .ItemWithPath(Path.Combine(file.PathStudent))
                                .Content.Request().GetHttpRequestMessage();

                            request.Method = HttpMethod.Put;
                            request.Content = stringContent;

                            // Ajout de la requête de chargement au batch
                            batchRequestContent.AddBatchRequestStep(request);


                        }

                        batchSize++;

                        // Envoyer la demande batch lorsque la taille maximale est atteinte
                        if (batchSize == 20)
                        {
                            await _graphServiceClientApp.Batch.Request().PostAsync(batchRequestContent);

                            // Réinitialiser la demande batch pour le prochain groupe de fichiers
                            batchRequestContent = new BatchRequestContent();
                            batchSize = 0;
                        }

                    }
                    if (batchSize > 0)
                    {
                        await _graphServiceClientApp.Batch.Request().PostAsync(batchRequestContent);

                        // Réinitialiser la demande batch pour le prochain groupe de fichiers
                        batchSize = 0;
                    }



                }

            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error uploading: {ex.ToString()}");
            }

        }

I did try to use MemoryStream and some others things just after file.FormFile.OpenReadStream() but it does the same things, no files and folder or just the folder and the file but no content. I did check on the net to see if someone have the same problem but i didn't see any answer that could help me resolve my problem. Can please someone help me or give me advice on what i do wrong ? Thank you very much :)

1

There are 1 answers

1
Megane Niama On

As suggested, i did some change in my code

public async Task BatchUploadFileAsync(string DriveID, GetAllFilesToUpload filesToUpload)
    {
        int batchSize = 20;

        var batchesOfFiles = new List<List<FileDatatoUpload>>();
        var currentBatch = new List<FileDatatoUpload>();

        foreach (var file in filesToUpload.Files)
        {
            currentBatch.Add(file);

            if (currentBatch.Count == batchSize)
            {
                batchesOfFiles.Add(currentBatch);
                currentBatch = new List<FileDatatoUpload>();
            }
        }

        if (currentBatch.Count > 0)
        {
            batchesOfFiles.Add(currentBatch);
            currentBatch = new List<FileDatatoUpload>();
        }

        try
        {

            List<System.IO.Stream> streams = new List<System.IO.Stream>();

            foreach (var batchFiles in batchesOfFiles)
            {
                var batchRequestContent = new BatchRequestContent();
                foreach (var file in batchFiles)
                {
                    // Créer et ouvrir le stream
                    var fileStream = file.FormFile.OpenReadStream();

                    var fileToWrite = System.IO.File.Create("D:yourFileName.pdf");

                    // This will copy the content of your fileStream to fileToWrite
                    fileStream.CopyTo(fileToWrite);

                    // Ensure that all data has been flushed to the disk and close the file
                    fileToWrite.Close();

                    // Ajouter le stream à la liste
                    streams.Add(fileStream);

                    Console.WriteLine($"Uploading file {file.FormFile.FileName} to {file.PathStudent}");

                    //using (var fileStream = file.FormFile.OpenReadStream())
                    //{
                    string encodedPath = Uri.EscapeDataString(file.PathStudent);

                    var request = _graphServiceClientApp.Users["userId"].Drive.Root
                            .ItemWithPath(Path.Combine(encodedPath))
                            .Content.Request().GetHttpRequestMessage();

                        request.Method = HttpMethod.Put;
                        request.Content = new StreamContent(fileStream);
                        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

                    Console.WriteLine($"Request URI: {request.RequestUri}");

                    // Add upload request to batch
                    batchRequestContent.AddBatchRequestStep(request);
                    //}
                }

                // Send the batch request
                var response = await _graphServiceClientApp.Batch.Request().PostAsync(batchRequestContent);
                Console.WriteLine($"Response status code: {response.GetResponsesAsync().Status}");
                Console.WriteLine($"Response content: {response.GetResponsesAsync().Result.Values}");


            }

            // Fermer tous les streams
            foreach (var stream in streams)
            {
                stream.Close();
            }
        }
        catch (ServiceException ex)
        {
            Console.WriteLine($"Error uploading: {ex.ToString()}");
        }
    }

        

I did try to check on my filestream as well and it seems fine, but i found an error i didn't see that could help me advance a little

Request URI: https://graph.microsoft.com/v1.0/users/emailId/drive/root:/E-Portfolio%2FAcadémique%2F1113254-RDNSemester-2020-2021-PGE3A-EN-S2.pdf:/content

and the error i am getting :

Error uploading: Status Code: 0

Microsoft.Graph.ClientException: Code: invalidRequest Message: Unable to deserialize content.

---> System.Text.Json.JsonReaderException: '%' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.