如何将服务器中的文件下载到访问nodeJS服务器中的页面的机器上?

我正在使用ExpressJS,我一直在尝试这个:

app.get('/download', function(req, res){

  var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');

  res.setHeader('Content-Length', file.length);
  res.write(file, 'binary');
  res.end();
});

但是我无法获得文件名和文件类型(或扩展名)。有人能帮我一下吗?


当前回答

使用res.download ()

它以“附件”的形式传输路径上的文件。例如:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

阅读更多关于res.download()

其他回答

使用res.download ()

它以“附件”的形式传输路径上的文件。例如:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

阅读更多关于res.download()

在快车4号。x时,Response有一个attachment()方法:

res.attachment();
// Content-Disposition: attachment

res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png

我是这样做的:

创建文件 发送文件到客户端 删除文件

代码:

let fs = require('fs');
let path = require('path');

let myController = (req, res) => {
  let filename = 'myFile.ext';
  let absPath = path.join(__dirname, '/my_files/', filename);
  let relPath = path.join('./my_files', filename); // path relative to server root

  fs.writeFile(relPath, 'File content', (err) => {
    if (err) {
      console.log(err);
    }
    res.download(absPath, (err) => {
      if (err) {
        console.log(err);
      }
      fs.unlink(relPath, (err) => {
        if (err) {
          console.log(err);
        }
        console.log('FILE [' + filename + '] REMOVED!');
      });
    });
  });
};

对于静态文件,如pdf, Word文档等,只需在配置中使用Express的静态函数:

// Express config
var app = express().configure(function () {
    this.use('/public', express.static('public')); // <-- This right here
});

然后把你所有的文件放到public文件夹里,例如:

/public/docs/my_word_doc.docx

然后一个常规的旧链接将允许用户下载它:

<a href="public/docs/my_word_doc.docx">My Word Doc</a>

你可以使用res.sendFile()…Sample-download.xlsx应该和这个函数在同一个目录下。

const downloadFile = (req,res) => {   
            var options = {
              root: path.join(__dirname),
            };
            
            let fileName = "Sample-download.xlsx";
            res.sendFile(fileName, options, function (err) {
              if (err) {
                console.log(err);
                return res.status(500).json({ success: false, message: "internal server error. please try again later" });
            
              } else {
                console.log("Sent:", fileName, "at", new Date().toString());
              }
            });
    }