最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Downloading a file sent in response to a POST request via nodejs? - Stack Overflow

programmeradmin6浏览0评论

I'm having trouble issuing a POST mand that downloads a file.

On the client side, I'm trying to POST to a specific URL, including a param that specifies the file to download.

var req = $.ajax({
    type: 'POST',
    url : '/click',
    data: { 'path' : filename }
   });
req.done(function(data) {
// Download the file here?

The server eventually fires off a method which does this:

function downloadFile(req, res) {
  var dir = req.session.currentdir + req.body.path;
  mimetype = (shell.exec("file --mime-type '" + dir + "'", {silent:true}).output);
  mimetype = mimetype.substring(mimetype.indexOf(": ") + 2, mimetype.length);

  var stat = fs.statSync(dir);
  res.writeHead(200, {'Content-Type' : mimetype,
                      'Content-Length': stat.size });
  var fileStream = fs.createReadStream(dir);
  fileStream.pipe(res);
};

Now I can't seem to get the client side to accept the file I'm trying to pipe back . . it just hangs for an incredibly long time before closing. What is the appropriate way to get the client to download the file I'm trying to send back?

Much thanks for taking the time to read.

I'm having trouble issuing a POST mand that downloads a file.

On the client side, I'm trying to POST to a specific URL, including a param that specifies the file to download.

var req = $.ajax({
    type: 'POST',
    url : '/click',
    data: { 'path' : filename }
   });
req.done(function(data) {
// Download the file here?

The server eventually fires off a method which does this:

function downloadFile(req, res) {
  var dir = req.session.currentdir + req.body.path;
  mimetype = (shell.exec("file --mime-type '" + dir + "'", {silent:true}).output);
  mimetype = mimetype.substring(mimetype.indexOf(": ") + 2, mimetype.length);

  var stat = fs.statSync(dir);
  res.writeHead(200, {'Content-Type' : mimetype,
                      'Content-Length': stat.size });
  var fileStream = fs.createReadStream(dir);
  fileStream.pipe(res);
};

Now I can't seem to get the client side to accept the file I'm trying to pipe back . . it just hangs for an incredibly long time before closing. What is the appropriate way to get the client to download the file I'm trying to send back?

Much thanks for taking the time to read.

Share Improve this question edited May 2, 2012 at 8:26 kjb asked May 2, 2012 at 8:07 kjbkjb 3,2054 gold badges25 silver badges30 bronze badges 1
  • I am facing same problem. I am getting the data in %PDF-1.4 %���� {more data} %%EOF, but how should i download the file. – Mohit Pandey Commented Aug 8, 2014 at 14:00
Add a ment  | 

1 Answer 1

Reset to default 5

1. resp.setHeader( "Content-Disposition", "attachment; filename=\"xxxx.xxx\"" );

2. better to use Get

发布评论

评论列表(0)

  1. 暂无评论