【问题标题】:Unable to download the file from Node.js using the POST request无法使用 POST 请求从 Node.js 下载文件
【发布时间】:2020-08-21 08:28:11
【问题描述】:

我发现了一些与此相关的问题,但答案对我不起作用,所以在这里发布相同的问题。

我有一些以编程方式创建并显示在 Textarea 中的 XML 内容。我需要一个选项来将其导出或下载到本地系统。所以我使用POST 请求将这些数据发送到NODE.JS,在那里我创建了我的XML 文件并尝试下载它。我知道如果我使用GET 它会直接工作,但使用POST 它会失败。有什么办法可以做到吗?

这是我的代码:

Angularjs POST 请求: 单击时我有一个按钮,我将所有 XML 数据传递给我的 NODE.js 函数:

$scope.ExportXML    =   function(XMLContent){
    var XMLContent  =   XMLContent;
    
    $http({
        url     :   "/ExportData",
        method  :   "POST",
        data    :   XMLContent
    }).success(function(data, status, headers, config) {
        console.log(data);
        console.log("Data Exported");
        window.location.assign(data);
        $window.open(data);
    }).error(function(error, status, headers, config) {
        console.log('ERROR: could not download file');
        console.log(error)
    });
}

我的 Node.js 函数将使用数据创建 XML 文件:

const fs        =   require('fs');
const path      =   require('path');
const reqPath   =   path.join(__dirname, '../');

exports.exportfile      =   function(req,res)
{   
    var ContentData     =   req.body;
    var FileName        =   "XMLDATA.xml";  
    
    fs.appendFile(FileName, ContentData, function (err)
    {
        const FilePath = reqPath+FileName;
        res.download(FilePath);
    })
}

正如您从 ANGULARJS 的成功功能中看到的那样,我尝试了几件事,但都没有奏效。我尝试使用callback(FilePath); 发回文件的路径,然后我尝试使用$window.open(data); 下载文件,但我收到以下错误Not allowed to load local resource:

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: javascript node.js angularjs export http-post


    【解决方案1】:

    经过一番搜索,我能够做到。我没有使用 POST 将 DATA 发送到 NODE.JS,而是尝试在我的 AngularjS 函数中创建文件并从那里自己下载它。如果有人在这里寻找解决方案,那就是:

    //Export the contents of XML to text file
    $scope.ExportXML    =   function(XMLContent){
        
        var filename = 'HelloWorld.xml'       
        var blob = new Blob([XMLContent], {type: "text/xml"});
        if (window.navigator && window.navigator.msSaveOrOpenBlob)
        {
            window.navigator.msSaveOrOpenBlob(blob, filename);
        }
        else
        {
            var e                   =   document.createEvent('MouseEvents'),
            a                       =   document.createElement('a');
            a.download              =   filename;
            a.href                  =   window.URL.createObjectURL(blob);
            a.dataset.downloadurl   =   ['text/json', a.download, a.href].join(':');
            e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 2012-10-11
      • 1970-01-01
      • 2021-08-21
      • 2015-06-26
      相关资源
      最近更新 更多