简体   繁体   English

从NodeJS发送文件作为对Jquery AJAX的响应

[英]Send a file from NodeJS as response to Jquery AJAX

I'm developing a web application where user clicks on a button, and a Jquery AJAX call goes to NodeJS server which in turn fetches the records from Elastic Search. 我正在开发一个Web应用程序,其中用户单击一个按钮,然后Jquery AJAX调用转到NodeJS服务器,该服务器依次从Elastic Search中获取记录。 I want these records to be written into a CSV file and send this file to AJAX as response being available for download on browser. 我希望将这些记录写入CSV文件并将此文件发送到AJAX,作为可在浏览器上下载的响应。 How can I achieve this? 我该如何实现?

var fs = require('fs');    
var stream = fs.createReadStream(pathToFile);
stream.on('error', function(){ 
    console.log('404  -------- ', pathToFile);
});
stream.pipe(res);


var destroy = require('destroy'); // nam i destroy --save
var onFinished = require('on-finished'); // nam i on-finished --save
onFinished(res, function (err) {
    destroy(stream)
})
$(document).ready(function() {
$(".export").on('click',function(){
    var project_id="<?php echo $_GET['project_id'];?>";
    $.ajax({
        type:"GET",
        url: 'https://work.readycontacts.com/True_Validate/download_file.php',
        data: "project_id=" + project_id,
            success:function(data){
                console.log(data);
            }
    });
return false;
});

}); });

export is the function that is bean click and you can replace download_file.php with your nodejs download code file export是单击bean的函数,您可以用nodejs下载代码文件替换download_file.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM