nodejs + express 实现 http文件下载服务程序,
主要包括两个功能:指定目录的文件列表,某个文件的下载。
假设已经安装好 nodejs ;
cd /js/node_js ; 安装在当前目录的 node_modules/
npm install express --save
npm install express-generator --save
D:\js> node node_js/node_modules/express-generator -e blog
create : blog\create : blog\public\create : blog\public\javascripts\create : blog\public\images\create : blog\public\stylesheets\create : blog\public\stylesheets\style.csscreate : blog\routes\create : blog\routes\index.jscreate : blog\routes\users.jscreate : blog\views\create : blog\views\error.ejscreate : blog\views\index.ejscreate : blog\app.jscreate : blog\package.jsoncreate : blog\bin\create : blog\bin\www
cd blog
install dependencies:
> npm install
npm notice created a lockfile as package-lock.json. You should commit this file.
added 54 packages from 38 contributors and audited 55 packages in 8.769s
编写模板文件 blog/views/files.ejs 如下
<!DOCTYPE html>
<html><head><title>下载文件选择</title></head><body><h1>请选择下载文件:</h1><% if(files.length>0) {%><ul><% files.forEach(function(file){ %><li><a href="/file/<%- file %>" target="_blank"><%- file %></a></li><%})%></ul><%} else {%><p>没有可下载文件…</p><%}%></body>
</html>
编写web服务程序 blog/expres_download.js 如下
//var http = require('http');
var express = require('express');
var fs = require('fs');
var path = require('path');
var logger = require('morgan');
var app = express();// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));// 首页
app.get('/', function(req,res){res.end('<a href="/files"> 文件列表 </a>');
});// 指定目录
const dir = "/Books";
// 显示指定目录的文件列表
app.get('/files', function(req, res, next) {// ls 文件目录//var filePath = path.join(__dirname, './');var filePath = path.join(dir, './');fs.readdir(filePath, function(err, results){if(err) throw err;if(results.length>0) {var files = [];results.forEach(function(file){if(fs.statSync(path.join(filePath, file)).isFile()){if (path.extname(file) === '.pdf'){files.push(file); //仅显示.pdf文件}}});res.render('files', {files:files});} else {res.end('当前目录下没有文件');}});
});// 实现文件下载
app.get('/file/:fileName', function(req, res, next) { var fileName = req.params.fileName;var filePath = path.join(dir, fileName);var stats = fs.statSync(filePath);if(stats.isFile()){res.set({'Content-Type': 'application/octet-stream','Content-Disposition': 'attachment;','Content-Length': stats.size});//'Content-Disposition': 'attachment; filename='+encodeURI(fileName),fs.createReadStream(filePath).pipe(res);} else {res.end('404');}
});app.listen(8080, "127.0.0.1", function() {console.log('web server 正在运行 http://127.0.0.1:8080')
});
运行 node expres_download.js