NodeJS下載文件實例

轉自:https://www.cnblogs.com/lishuyi/p/5213505.html

var http = require('http');
var express = require('express');
var fs=require("fs");
var app = express();

app.get('/info/*', function(req, res, next){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('hello file.txt');
})

app.get('/download/*', function (req, res, next) {
 //第一種方式
  //var f="./file.txt";
  ////var f = req.params[0];
  //f = path.resolve(f);
  //console.log('Download file: %s', f);
  //res.download(f);

  //第二種方式
  var path="./file.txt"
  var f = fs.createReadStream(path);
  res.writeHead(200, {
    'Content-Type': 'application/force-download',
    'Content-Disposition': 'attachment; filename=file.txt'
  });
  f.pipe(res);
});

http.createServer(app).listen(3000);

file.txt 放在服務器端

url --> localhost:3000/info/file.txt
url --> localhost:3000/download/file.txt

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章