用nodejs写了个HTTP 文件服务器,好蛋疼
发布于 11 年前 作者 dingwei 14792 次浏览 最后一次编辑是 8 年前

现在express里有个文件名的bug, res.sendfile, res.download之类的都有, 不支持路径中有中文名称包括文件名 后端用mongodb存文件全路径,下载时只通过id传, 原来想直接传全文件路径比如C:\works\a.txt,后来发现不行,好象security限制住了,根本不会route到/download/:filename的处理,直接显示无法GET…

主要两个页面,一个Add file, 一个显示所有文件,点击任意一个即可下载

exports.down = function(req, res){

var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var path = require('path');
var ObjectID = require('mongodb').ObjectID;

MongoClient.connect("mongodb://localhost:27017/filelist", function(err, db) {
	if (!err) {
		console.log("We are connected.");
	}
	var fileid = req.params.id;

	var collection = db.collection('filelink');
	collection.findOne({"_id": ObjectID(fileid)}, function(err, item) {
		var filepath = item["file"];
		var filebase = path.basename(filepath);
		//console.log(filepath);
		//console.log(filebase);
		res.download(filepath,filebase);

	
	});
});

};

10 回复

标题是lz自嘲?

楼主不蛋疼,谁蛋疼! 一个简单的文件服务器都要搬出mongodb

大炮打蚊子

要保存状态啊,象HFS一样, 如果没有persistence, 下次开启时又没有了,上次share的列表, 你用文件去存一个列表也是一样。。。。 这个是可以共享任意磁盘上的文件的,不是那个public文件夹share, 设置一下就可以了

我也觉得,原来想用sqlite3, 结果那个傻X的sqlite npm package装不起来, 老是在node-gyp编译时出错 有空再试试

@dingwei

可下载任意文件:

var express = require('express');
var http = require('http');
var path = require('path');

var app = express();

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

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

// 在浏览器中打开 http://127.0.0.1/download/c:/windows/notepad.exe
// 即可下载

@leizongmin 不错写的很精简, 有个问题是我需要保存一个列表,下次打开文件服务器时可以直接加载,另外你这个危险性太高,随便哪个程序都直接下载了汗。。。。 学习了, 用这个/download/* 用*不错, 我之前用的/download/:filename这样,怎么传全路径都不行,/download/C:/windows/notepad.exe直接会返回cannot get … 都不会跳入这个app.get处理程序 不知道怎么回事 我想实现跟HFS (HTTP File Server类似的功能), 每次保存上次的服务的文件列表, 下次自动加载,比较方便

@leizongmin 对了, 依然中文名乱码,这个是express的问题,用http模块就没问题

发一下写来自己用的非常简单的静态文件服务器,不需要express,mongodb,sqlite…

var PORT = 8090;
var MIME = {
    'htm':  'text/html',
    'html': 'text/html',
    'css':  'text/css',
    'gif':  'image/gif',
    'ico':  'image/x-icon',
    'jpg':  'image/jpeg',
    'js':   'text/javascript',
    'png':  'image/png',
    'rar':  'application/x-rar-compressed',
    'txt':  'text/plain',
    'json': 'text/plain',
    'jar':  'application/java-archive'
};
var dir = process.argv[2];
var ROOT = dir ? dir : process.cwd();

var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');

http.createServer(function(request, response) {
    var pathname = url.parse(request.url).pathname;
    var realpath = pathname !== '/' ? ROOT + pathname : __filename;
    var extname = path.extname(realpath).slice(1);
    var contentType = 'text/plain';

    if (extname && MIME[extname]) {
        contentType = MIME[extname];
    }

    fs.exists(realpath, function(exists) {
        if (exists) {
            fs.readFile(realpath, function(err, data) {
                if (err) throw err;

                response.writeHead(200, {'Content-Type': contentType});
                response.write(data);
                response.end();
            });
        } else {
            response.writeHead(404, {'Content-Type': 'text/plain'});
            response.write('Not Found');
            response.end();
        }
    });

}).listen(PORT);

console.log('simple static file server runing at port: ' + PORT + '.');

__filename  不如改成index.html

回到顶部