简体   繁体   English

如何生成带有表单数据的 .txt 文件并使用 Node JS 下载?

[英]How to generate a .txt file with form data and download it with Node JS?

The system has a form, on the side of the backend I recover that data, what I can't do is download that data in a .txt file.系统有一个表格,在后端我恢复那些数据,我不能做的是将这些数据下载到一个 .txt 文件中。

I was using fs.writefile () , but when the system is uploaded in the cloud it does not access the destination folder.我正在使用fs.writefile () ,但是当系统上传到云端时,它不会访问目标文件夹。

   var new_ingreso = new Ingreso(req.body);
   //I want to download the data from req.body in a file.txt
   fs.writeFile(
      'nameFile.txt',
      new_ingreso.nameUser,
      error => {
        if (error)
          console.log(error, 'el archivo no fue creado');
        else
          console.log('El archivo fue creado');
        });
  }

The file is created without problems what I want is to know if there is any way that this file can be downloaded or if there is another way to download.该文件的创建没有问题,我想知道是否有任何方法可以下载该文件,或者是否有其他方法可以下载。

He's seeing a way but I'm not sure how to continue.他看到了一种方法,但我不知道如何继续。

var file = fs.writeFile(....);

You need to create a route like this.您需要创建这样的路线。 You need to do something with the file path to find your file.你需要对文件路径做一些事情来找到你的文件。 No security, code not tested, but it gives you the idea of how to do it.没有安全性,代码没有经过测试,但它让你知道如何去做。

See https://expressjs.com/en/api.html#res.sendFilehttps://expressjs.com/en/api.html#res.sendFile

get('file', (req, res) => {
   res.sendFile('nameFile.txt', options, function (err) {
    if (err) {
      next(err)
    } else {
      console.log('Sent:', 'nameFile.txt')
    }
  })
})

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

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