2

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Do you get any errors in browser's console? Information you've provided is not enough. – Aleksei Budiak Aug 25 '17 at 08:37
  • I didnt get any error. Am getting response, but i want it to download as png. –  Aug 25 '17 at 10:40
  • res::: {"req":{"method":"GET","url":"api/downloadDoc?id=599d8c4fd342a9bf7264b2be","headers":{}},"xhr":{},"text":"�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0002�\u0000\u0000\u0002�\b\u0006\u0000\u0000\u0000�{Y�\u0000\u0000\u0000\u0001sRGB\u0000��\u001c�\u0000\u0000\u0000\u0004gAMA\u0000\u0000��\u000b�a\u0005\u0000\u0000\u0000\tpHYs\u0000\u0000\u000e�\u0000\u0000\u000e�\u0001�o�d\u0000\u0000 –  Aug 25 '17 at 10:41
  • this is the response am getting.. –  Aug 25 '17 at 10:41
  • ,"statusCode":200,"status":200,"statusType":2,"info":false,"ok":true,"redirect":false,"clientError":false,"serverError":false,"error":false,"accepted":false,"noContent":false,"badRequest":false,"unauthorized":false,"notAcceptable":false,"forbidden":false,"notFound":false,content-type":"image/png"},"header":{"date":"Fri, 25 Aug 2017 10:38:49 GMT","content-disposition":"attachment; filename=Capture.PNG","transfer-encoding":"chunked","content-type":"image/png"},"type":"image/png","links":{},"body":null} –  Aug 25 '17 at 10:54

1 Answers1

1

Use the below line of code in the else part.

window.location= 'api/CommercialInvoice?item=' + item.id,'';
element.click();
Karthikeyan
  • 1,927
  • 6
  • 44
  • 109