Search code examples
reactjssuperagent

File download using SuperAgent


I'm trying to download files from server using SuperAgent. Please find the code below.

downloadDocument(fileIdMongo) {
    var request = require('superagent');
    var apiBaseUrl = "api/downloadDoc";
    var self = this;
    var req = request.get(apiBaseUrl);
    req.query({ id: fileIdMongo })
    req.end(function(err, res) {
        if (err) {
            console.log("error ocurred");
        } else {
            var blob = new Blob([res.text], {
                type: 'text/csv/jpeg/jpg/png/pdf/docx/doc;charset=utf8;'
            });
            var element = document.createElement('a');
            document.body.appendChild(element);
            element.download = "Capture.PNG";
            element.href = window.URL.createObjectURL(blob);
            element.style.display = '';
            element.click();
        } 
    });
}

I'm trying to get a .png file from the server. I tested server with PostMan rest client. I'm able to get the .png file. But the file is not visible when using SuperAgent.


Solution

  • Use the below line of code in the else part.

    window.location= 'api/CommercialInvoice?item=' + item.id,'';
    element.click();