通过nodejs将文件上传到mongodb

要用到node写后台的文件上传,不知道有没有java的那些接口,百度了一下,先存下来,后面尝试一下~

后台真的好难哇大哭

这里要用到一些组件,通过npm安装一下 gridform和gridfs-stream

上传POST到 :http://yourUrl/upload

上传后的文件,可以通过文件名和ID来访问,比如:http://yourUrl/id/xxxxxx  OR http://yourUrl/filename

 

建好下面这两个文件后,运行node test.js启动

复制代码
//test.js

var
mongo = require('mongodb'), FileServer=require('./fileserver'), Server = require('mongodb').Server; var db = new mongo.Db('test', new Server("127.0.0.1", 27017,{auto_reconnect:true})); var fileServer = FileServer(db); fileServer.start(8888);
复制代码

 

 

 

复制代码
//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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值