通过nodejs将文件上传到mongodb

//fileserver.js

var http = require("http"),
    url = require("url"),
    mongo = require('mongodb'),
    path = require("path"),
    ObjectID = require('mongodb').ObjectID,
    Grid = require('gridfs-stream'),
    gridform = require('gridform'),
    fs = require("fs"),
    GridStore = require('mongodb').GridStore;


function FileServer(db) {
    if (!(this instanceof FileServer)) return new FileServer(db);
    this.db = db;
}

FileServer.prototype.start = function start(listenport) {
    var me = this;
    me.db.open(function(err) {
        if (err) {
            console.log(err);
            return;
        }
        app.listen(listenport, "127.0.0.1");
        console.log("Server running at http://127.0.0.1:" + listenport);

    });

    var app = http.createServer(function(req, res) {

        var pathname = url.parse(req.url).pathname;
        //upload
        if (pathname.indexOf('/upload') >= 0 && 'POST' == req.method) {
            gridform.db = me.db;
            gridform.mongo = mongo;
            var outObj;
            var form = gridform();
            form.parse(req, function(err, fields, files) {
                if (err) {
                    outObj = {
                        "status": 0,
                        "message": err
                    }

                } else {
                    for (var obj in files) {
                        outObj = {
                            status: 1,
                            data: {
                                name: files[obj].name,
                                id: files[obj].id.toString(),
                                url: 'http://' + req.headers.host + '/id/' + files[obj].id.toString()
                            }
                        };
                    }

                }
                console.log('received upload..');
                me.responMsg(res, 200, JSON.stringify(outObj));
            });

        } else if (pathname != '/') { //download///
            var filename, fileId, delPos, idPos, strId;

            delPos = pathname.indexOf('/delete/');
            idPos = pathname.indexOf('/id/');
            //通过ID匹配文件
            if (idPos >= 0) {
                strId = pathname.substr(idPos + 4, pathname.length - idPos + 1);
                filename = {
                    _id: strId
                };
                fileId = ObjectID(strId);
            } else {
                filename = pathname.replace('/', '');
            }
            console.log('get file:' + filename);
            //优先查找磁盘中的文件
            var realPath = "files" + pathname;


            path.exists(realPath, function(exists) {
                if (exists) {
                    fs.readFile(realPath, "binary", function(err, file) {
                        if (err) {
                            me.responMsg(res, 500, err);
                        } else {
                            var ext = path.extname(realPath);
                            ext = ext ? ext.slice(1) : 'unknown';
                            var contentType = mime[ext] || "text/plain";
                            res.writeHead(200, {
                                'Content-Type': contentType
                            });
                            res.write(file, "binary");
                            res.end();
                        }
                    });
                } else {
                    // Verify that the file exists
                    me.exist(me.db, fileId || filename, function(err, result, item) {
                        if (!result) {
                            me.responMsg(res, 404, "文件不存在");
                            return;
                        }
                        if (delPos >= 0) {
                            GridStore.unlink(me.db, item._id, function(err) {
                                me.responMsg(res, 200, 'success')
                            });
                        } else {
                            var gfs = Grid(me.db, mongo);
                            var readstream = gfs.createReadStream(filename);
                            var ext = item.filename.split('.');
                            ext = ext ? ext[ext.length-1] : 'unknown';
                            var contentType = mime[ext] || "text/plain";

                            res.setHeader("Content-Type", contentType);
                            readstream.pipe(res);
                        }
                    });
                }
            });

        } else {
            res.setHeader("Content-Type", "text/html");
            res.end(
                '<form method="post" action="/upload" enctype="multipart/form-data">' + '<input type="file" name="text">' + '<input type="submit" value="upload">' + '</form>');
        }

        
    });
}

FileServer.prototype.responMsg = function responMsg(response, status, msg) {
    response.writeHead(status, {
        'Content-Type': 'text/plain;charset=utf-8'
    });

    response.end(msg);
}

//覆盖了驱动里原始的exist方法,将找到的item也返回来
FileServer.prototype.exist = function exist(db, fileIdObject, rootCollection, callback) {
    var args = Array.prototype.slice.call(arguments, 2);
    callback = args.pop();
    rootCollection = args.length ? args.shift() : null;

    // Fetch collection
    var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
    db.collection(rootCollectionFinal + ".files", function(err, collection) {
        // Build query
        var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]') ? {
            'filename': fileIdObject
        } : {
            '_id': fileIdObject
        }; // Attempt to locate file
        collection.find(query, function(err, cursor) {
            cursor.nextObject(function(err, item) {
                callback(null, item == null ? false : true, item);
            });
        });
    });
};

var mime = {

    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml",
    "doc": "application/msword",
    "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "xls": "application/vnd.ms-excel",
    "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

};

module.exports = exports = FileServer;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于nodejs express mongodb multer实现的文件上传、存储、分页、管理功能的示例代码: 1.安装依赖 ```shell npm install express multer mongodb ``` 2.引入依赖 ```javascript const express = require('express'); const multer = require('multer'); const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectId; const url = 'mongodb://localhost:27017'; const dbName = 'fileUpload'; const upload = multer({ dest: 'uploads/' }); const app = express(); ``` 3.连接数据库 ```javascript MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) { if (err) throw err; console.log("Connected successfully to server"); const db = client.db(dbName); // ... }); ``` 4.上传文件 ```javascript app.post('/upload', upload.single('file'), function(req, res, next) { const file = req.file; const collection = db.collection('files'); collection.insertOne(file, function(err, result) { if (err) throw err; res.send('File uploaded successfully!'); }); }); ``` 5.获取文件列表 ```javascript app.get('/files', function(req, res, next) { const collection = db.collection('files'); const pageNum = parseInt(req.query.pageNum) || 1; const pageSize = parseInt(req.query.pageSize) || 10; const skip = (pageNum - 1) * pageSize; collection.find().skip(skip).limit(pageSize).toArray(function(err, docs) { if (err) throw err; res.send(docs); }); }); ``` 6.删除文件 ```javascript app.delete('/files/:id', function(req, res, next) { const collection = db.collection('files'); const id = req.params.id; collection.deleteOne({ _id: ObjectId(id) }, function(err, result) { if (err) throw err; res.send('File deleted successfully!'); }); }); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值