直接上代码,这是第一版,可以判断扩展名
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