Adding token to the beforeDownload Event doesnot works whereas it works for beforeSend Event.

const handleBeforeDownload = (args: BeforeDownloadEventArgs) => { if (token && args.ajaxSettings) { (args.ajaxSettings as FileManagerAjaxSettings).beforeSend = (innerArgs: { httpRequest: XMLHttpRequest }) => { innerArgs.httpRequest.setRequestHeader('Authorization', `Bearer ${token}`); }; } };


1 Reply

SR Subalakshmi Ramachandran Syncfusion Team August 16, 2024 12:52 PM UTC

Hi Ofer,

Based on your shared details, we have understood that you are trying to pass the authentication token in the beforeDownload event of FileManager component.


Currently, we have used the form submit for download operations of FileManager. So, in Download operation, we are unable to add the header token for FileManager component. To achieve your requirement, we need to prevent the default Download action and make an ajax request through beforeDownload event to perform verifications on server side . If the verification succeeds, download operation can be performed by invoking form submit, else download failure exception will be returned.

Refer to the below code snippet.

[index.js]

const beforeDownload = (args) => {

    args.cancel = true;

    var obj = {

      action: 'download',

      path: args.data.path,

      names: args.data.names,

      data: args.data.data,

    };

    var xhr = new XMLHttpRequest();

    xhr.open('POST', 'http://localhost:62869/api/FileManager/Download', true);

    xhr.responseType = 'blob';

    xhr.onload = function () {

      if (this.status === 200) {

        var name = '';

        // Getting file name from content-disposition header

        let header = xhr.getResponseHeader('Content-Disposition');

        if (header && header.indexOf('attachment') !== -1) {

          var regex = /name[^;=\n]*=((['"]).*?\2|[^;\n]*)/;

          var matches = regex.exec(header);

          if (matches != null && matches[1])

            name = matches[1].replace(/['"]/g, '');

        }

        //saving the file locally using anchor tag

        var blob = new Blob([this.response], {

          type: xhr.getResponseHeader('Content-Type'),

        });

        var anchorUrl = window.URL.createObjectURL(blob);

        if (name) {

          var anchor = document.createElement('a');

          anchor.rel='nofollow' href = anchorUrl;

          anchor.download = name;

          anchor.click();

        } else {

          window.location = anchorUrl;

        }

        setTimeout(function () {

          URL.revokeObjectURL(anchorUrl);

        }, 100);

      } else {

        console.log('Request failed');

      }

    };

    var fdata = JSON.stringify(obj);

    xhr.setRequestHeader('Custom-Header', 'Syncfusion');

    xhr.send(fdata);

  };

 



Sample: filemanager-dowload-token - StackBlitz

Regards,

Suba R.


Loader.
Up arrow icon