nodejs + express 实现 http文件下载服务程序

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.css
   create : blog\routes\
   create : blog\routes\index.js
   create : blog\routes\users.js
   create : blog\views\
   create : blog\views\error.ejs
   create : blog\views\index.ejs
   create : blog\app.js
   create : blog\package.json
   create : 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 如下

html 复制代码
<!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 如下

javascript 复制代码
//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

相关推荐
Pu_Nine_920 小时前
JavaScript后端日志系统:使用Winston构建专业日志
后端·express·日志·commonjs·winston
GISer_Jing2 天前
深入解析Node.js中间件:从Express到Nest
中间件·node.js·express
沟通QQ:4877392783 天前
探索Matlab/Simulink污水废水处理仿真基准模型BSM1
express
z***3354 天前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
一字白首4 天前
Node.js 入门,进阶核心:CommonJS+ES6 模块化、包、Express 与跨域
node.js·es6·express
水冗水孚5 天前
效能工具十之接入deepseek实现AI学习PDF文档读后感文件批量生成功能
openai·express·deepseek
w***74175 天前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
weixin79893765432...6 天前
Vue + Express + DeepSeek 实现一个简单的对话式 AI 应用
vue.js·人工智能·express
D***y2018 天前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express
q***46411 天前
使用Node.js搭配express框架快速构建后端业务接口模块Demo
node.js·express