Bryan van Rijn
Bryan van Rijn

Reputation: 971

SharePoint SPFX: Unable to get property 'Context'

I'm working on a custom SPFX commandset. It opens a dialog with an iframe to an 3rth party platform. I'm able to receive a json through a postmessage. From this json, I convert it's data to a file, with it's proper metadata. All of this works like a charm... Except...

Now I want to upload this file to a document library, and it drives me crazy.
I'm referencing:

import "@pnp/polyfill-ie11";
import { ConsoleListener, Logger, LogLevel } from "@pnp/logging";
import { sp } from "@pnp/sp";
import { Web } from "@pnp/sp/webs";
import "@pnp/sp/webs";
import "@pnp/sp/files";
import "@pnp/sp/folders";
import { Base64 } from 'js-base64';

In my dialog component, I try to upload the file with web.getFolderByServerRelativeUrl. But this method is failing, and I really don't understand why.... Looking at the pnp reference (https://pnp.github.io/pnpjs/sp/files/), It seems like the right way.

var file = Base64.atob(response.Data);
console.log("File length : " + file.length);
let web = Web("https://MyTenant.sharepoint.com/sites/Customer"); // this is successful 

await web.getFolderByServerRelativeUrl("/sites/Customer/Shared%20Documents/")
    .files.add(response.fileName, file, true); // this fails

The context is set on the CommandSet onInit()

@override
  public onInit(): Promise<void> {
    Log.info(LOG_SOURCE, 'Initialized myCommandSet');
    pnpSetup({
      spfxContext: this.context
    });
    return Promise.resolve();
  }

Hope you guys and girls can point me in the right direction...

EDIT:

Error:

HTTP400: INVALID REQUEST - The request could not be processed by the server
 due to an invalid syntax
POST - https://MyDevTenant.sharepoint.com/sites/customer/
_api/web/getFolderByServerRelativeUrl
('%2Fsites%2Customer%2FShared%2520Documents%2F')
/files/add(overwrite=true,url='')

Is it the url from the documentlibrary that messes things up?

Upvotes: 0

Views: 1484

Answers (1)

Bryan van Rijn
Bryan van Rijn

Reputation: 971

Thanks to Willman for giving me a right direction. This did the trick:

import { sp, Web, IWeb } from "@pnp/sp/presets/all";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/files";
import "@pnp/sp/folders";

const web = await sp.web();
const list = sp.web.getList("Documents");
const listId = await list.select("Id")();
await sp.web.lists.getById(listId.Id).rootFolder.files.add(docname, file, true);

Upvotes: 0

Related Questions