Skip to Content

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);

2 Comments
You must be Logged on to comment or reply to a post.
  • 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.