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

setting file name for download response in node.js

本文关键字:响应 文件名 下载 设置 node js      更新时间:2023-09-26

如何为我下载的二进制文件设置一个文件名在下面的节点响应get请求,现在它下载文件并将其名称设置为req。Url字符串

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