Skip to Content
Author's profile photo Former Member

Set csrf token to SAPUI5 FileUploader control

Here is a quick and simple solution to set csrf token to sap.ui.unified.FileUploader control:

1) Since OData model supports csrf token handling, you can retrieve csrf token from OData model’s header:

var csrfToken = this.getView().getModel().oHeaders[‘x-csrf-token’];

2) Set the token to FileUploader header.  Say oUpload is the reference to your sap.ui.unified.FileUploader control.

2.1 Set SendXHR to true

oUpload.setSendXHR(true);

2.2 create header parameter with csrf token and add to FileUploader control header

var headerParma = new sap.ui.unified.FileUploaderParameter();

headerParma.setName(‘x-csrf-token’);

headerParma.setValue(csrfToken);

oUpload.addHeaderParameter(headerParma);

Assigned Tags

      2 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Nilay Ghosh
      Nilay Ghosh

      Hi Ken,
      Fetching the token this way throws an error in loading the application. This is considered an illegal syntax.

      Author's profile photo Former Member
      Former Member
      Blog Post Author

      Please do not try to retrieve CSRF token at onInit() method. The CSRF token is not ready at the application startup stage. Suggest to retrieve CSRF token at:

      1) onAfterRendering() or onUpdateFinished() after the model data has already retrieved from server.

      2) Or at the time when you do uploading.

      if (!this.csrfToken) {
      this.csrfToken = this.getView().getModel().oHeaders['x-csrf-token'];
      oUpload.setSendXHR(true);
      var headerParma = new sap.ui.unified.FileUploaderParameter();
      headerParma.setName('x-csrf-token');
      headerParma.setValue(this.csrfToken);
      oUpload.addHeaderParameter(headerParma);
      }
      oUpload.upload();

      Hope it helps.