Search code examples
pdffile-uploaduploadmicrosoft-graph-apimicrosoft-graph-files

How to upload pdf file to Sharepoint site using MicrosoftGraph


I'm trying to transfer a pdf stored on a mobile device to a Sharepoint site using Microsoft Graph API. The file is read as a base64 string and this string is set as the content of a file on the site.

I have been successful in transferring plain text files but unable to do so with pdfs. It seems like I’m just creating a plain text file with a .pdf extension (can change the extension to .txt and the file just contains the string version of the original file).

Any idea on how to specify that the string being transferred is an encoded version of the file and not just plain text? I'm assuming this is the case when uploading images or any non-.txt files, so any related advice would be helpful.

graphClient.api('/sites/{site-id}/drives/{drive-id}/root:/UploadedFile.pdf:/content')
            .header("content-type", "application/pdf")
            .put(fileContent)
            .then((response) => {
                console.log(response);
            });

Solution

  • I solved the problem. I converted the base64 string to binary using Buffer.

    const fileContentAsBinary = Buffer.from(fileContent, "base64");
    graphClient.api('/sites/{site-id}/drives/{drive-id}/root:/UploadedFile.pdf:/content')
                .header("content-type", "application/pdf")
                .put(fileContentAsBinary)
                .then((response) => {
                    console.log(response);
                });