0

I am facing en enconding issue when downloading a file from Sharepoint Online by an Azure function. So I have an Azure HTTP triggered function that calls Sharepoint Online to retrieve a file and download it. Here is how I call Sharepoint:

public dynamic DownloadFile(Guid fileUniqueId)
    {
        const string apiUrl = "{0}/_api/web/GetFileById('{1}')/$value";

        try
        {
            var fileInfo = GetFileInfo(fileUniqueId);
            if (string.IsNullOrEmpty(_sharepointSiteUrl)) return null;

            string api = string.Format(apiUrl, _sharepointSiteUrl, fileUniqueId.ToString());
            string response = new TokenHelper().GetAPIResponse(api);
            if (string.IsNullOrEmpty(response)) return null;

            
            return new {
                fileInfo.FileName,
                Bytes = Encoding.UTF8.GetBytes(response)
            };
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

And Here is the Azure App function that is called:

 string guidString = req.Query["id"];
        if (!Guid.TryParse(guidString, out var fileId))
            return new BadRequestResult();

        var fileManager = new FileManager();
        dynamic fileData = fileManager.DownloadFile(fileId);
        if (null == fileData) return new NotFoundResult();

        var contentType = (((string)fileData.FileName).ToUpper().EndsWith(".PNG") || ((string)fileData.FileName).ToUpper().EndsWith(".JPEG") || ((string)fileData.FileName).ToUpper().EndsWith(".JPG")) ? "image/jpeg" : "application/octet-stream";

        return new FileContentResult(fileData.Bytes, contentType)
        {
            FileDownloadName = fileData.FileName
        };

The file is succesfully downloaded but it seems corrupted as it says that the file type is not recognised. I think that it's an issue related to encoding. Does somebody sees what I'm doing wrong ?

Hubert Solecki
  • 2,611
  • 5
  • 31
  • 63

1 Answers1

0

Your code is using UTF8.GetBytes() to try and get the file content from SharePoint Online. You should instead use the CSOM method OpenBinaryDirect() like this:

var fileRef = file.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
using (var fileStream = System.IO.File.Create(fileName))
{
    fileInfo.Stream.CopyTo(fileStream);
}