【问题标题】:File download using SuperAgent使用 SuperAgent 下载文件
【发布时间】:2017-11-05 19:28:16
【问题描述】:

我正在尝试使用 SuperAgent 从服务器下载文件。请在下面找到代码。

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

我正在尝试从服务器获取.png 文件。我用 PostMan 休息客户端测试了服务器。我能够得到.png 文件。但是使用 SuperAgent 时文件是不可见的。

【问题讨论】:

  • 浏览器控制台是否出现错误?您提供的信息还不够。
  • 我没有收到任何错误。收到回复,但我希望它下载为 png。
  • 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
  • 这是我得到的回应..
  • ,"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","传输编码":"chunked","content-type":"image/png"},"type":"image/png","links":{},"body" :null}

标签: reactjs superagent


【解决方案1】:

在 else 部分使用下面的代码行。

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

【讨论】:

  • 下载失败有回调吗?
猜你喜欢
  • 2015-10-23
  • 2016-03-27
  • 2018-02-28
  • 2020-03-17
  • 2015-04-08
  • 2018-08-03
  • 2010-12-20
  • 2016-01-06
  • 2018-04-08
相关资源
最近更新 更多