首页 > Web开发 > 详细

Node.js 搭建HTTP服务器,提供文件下载

时间:2018-06-29 10:04:52      阅读:139      评论:0      收藏:0      [点我收藏+]

直接上代码,这是第一版,可以判断扩展名

 

var http = require(‘http‘);
var express = require(‘express‘);
var fs=require("fs");
var path=require("path");
var mime = require(‘mime‘);
var app = express();
var currDir = ‘F:\\Users\\djyk\\74dj.mp3‘;
app.get(‘*‘, function (req, res, next) {
  var reqpath = decodeURI(req.path);
  console.log(reqpath);
  var filepath = path.join(currDir,reqpath);
  fs.lstat(filepath, function(err, stat) {
    if(err){
      if (err.code === ‘ENOENT‘) {
        res.writeHead(404);
        res.end("404 Not Found");
        return;
      }
      res.writeHead(500);
      res.end(JSON.stringify(err));
      return;
    }
    if(stat.isDirectory()) {
      res.writeHead(403);
      res.end("403 Forbidden");
      return;
    }
    if (path.extname(filepath) !== ‘.mp3‘) {
      res.writeHead(400);
      res.end("400 Bad Request");
      return;
    }
    var f = fs.createReadStream(filepath);
    const row = {};
    row[‘Content-Type‘] = mime.getType(reqpath);
    row[‘Content-Disposition‘] = ‘attachment; filename=‘ + encodeURI(path.basename(reqpath));
    res.writeHead(200, row);
    f.pipe(res);
  });
});
http.createServer(app).listen(50074);

 

Node.js 搭建HTTP服务器,提供文件下载

原文:https://www.cnblogs.com/xiangxisheng/p/9241749.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!