Search code examples
javascriptnode.jsxmlsharepointpnp-js

How to upload a file xml with NodeJS v18 to a SharePoint Online?


I shouaite upload a file . xml in a folder of an online sharepoint, I only have the client_id the client_secret and the url of my sharepoint. Unfortunately, I can’t find a solution.

I tried to do it with pnp but the version is not compatible with nodejs 18 and I can’t do it with versions 3 & 4. I can’t find other methods or libraries that will allow me to do it.I want to upload my file to my sharepoint folder. Currently there is nothing that works


Solution

  • Here's a basic example of how to upload a file:

    const { ClientSecretCredential } = require('@azure/identity');
    const { Client } = require('@microsoft/microsoft-graph-client');
    
    const clientId = 'YOUR_CLIENT_ID';
    const clientSecret = 'YOUR_CLIENT_SECRET';
    const tenantId = 'YOUR_TENANT_ID';
    const siteId = 'YOUR_SITE_ID'; // This is the ID of your SharePoint site
    const targetFolderId = 'YOUR_TARGET_FOLDER_ID'; // This is the ID of the folder where you want to upload the file
    const filePath = 'PATH_TO_YOUR_XML_FILE'; // Path to the XML file you want to upload
    
    const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
    const client = Client.initWithMiddleware({
        authProvider: {
            getAccessToken: async () => {
                const token = await credential.getToken('https://graph.microsoft.com/.default');
                return token.token;
            },
        },
    });
    
    async function uploadFile() {
        try {
            const fileContent = fs.readFileSync(filePath);
            const fileName = path.basename(filePath);
            const response = await client.api(`/sites/${siteId}/drive/items/${targetFolderId}:/${fileName}:/content`)
                .put(fileContent);
            console.log('File uploaded successfully:', response);
        } catch (error) {
            console.error('Error uploading file:', error);
        }
    }
    
    uploadFile();