在node.js中设置下载响应的文件名

时间:2015-10-10 09:10:26

标签: javascript node.js http

如何在get请求的以下节点响应中为我下载的二进制文件设置文件名,现在它下载文件并将其名称设置为req.url string

.get(function (req, res) {
  var filename = path.join(process.cwd(), '');
  path.exists(filename, function (exists) {
    if (!exists) {
      res.writeHead(404, {
        "Content-Type": "text/plain"
      });
      res.write("File Not found: 404 Not Found\n");
      res.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) {
      filename += '/' + category + '/' + 'undo.png';
    }

    fs.readFile(filename, "binary", function (err, file) {
      if (err) {
        res.writeHead(500, {
          "Content-Type": "binary"
        });
        res.write(err + "\n");
        res.end();
        return;
      }

      res.writeHead(200);
      res.write(file, "binary");
      res.end();
    });
  });
});

1 个答案:

答案 0 :(得分:4)

.get(function (req, res) {
  var filename = path.join(process.cwd(), '');
  path.exists(filename, function (exists) {
    if (!exists) {
      res.writeHead(404, {
        "Content-Type": "text/plain"
      });
      res.write("File Not found: 404 Not Found\n");
      res.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) {
      filename += '/' + category + '/' + 'undo.png';
    }

    fs.readFile(filename, "binary", function (err, file) {
      if (err) {
        res.writeHead(500, {
          "Content-Type": "binary"
        });
        res.write(err + "\n");
        res.end();
        return;
      }

      res.writeHead(200, {
        "Content-Disposition": "attachment;filename=" + yourFilename,
        'Content-Type': 'image/png',
        'Content-Length': file.length
      });
      res.write(file);
      res.end();
    });
  });
});