var db = require('db'); var fs = require('fs'); var path = require('path'); var Evt = require('evt'); var User = require('user'); var Common = require('common'); var Images = db.images; function log(o) { console.log(o); } /* type File struct { FileId bson.ObjectId `bson:"_id,omitempty"` // UserId bson.ObjectId `bson:"UserId"` AlbumId bson.ObjectId `bson:"AlbumId"` Name string `Name` // file name Title string `Title` // file name or user defined for search Size int64 `Size` // file size (byte) Type string `Type` // file type, "" = image, "doc" = word Path string `Path` // the file path IsDefaultAlbum bool `IsDefaultAlbum` CreatedTime time.Time `CreatedTime` FromFileId bson.ObjectId `bson:"FromFileId,omitempty"` // copy from fileId, for collaboration } */ // 文件服务 var File = { // path是相对于项目路径 addImage: function(path, callback) { var me = this; var absolutePath = Evt.getBasePath() + '/' + path; me._addImage(Common.objectId(), absolutePath, callback); }, _addImage: function(fileId, absolutePath, callback) { // var absolutePath = Evt.getBasePath() + '/' + path; // 得到文件大小 var stat = fs.statSync(absolutePath); var paths = absolutePath.split('/'); var name = paths[paths.length-1]; var names = name.split('.'); var ext = names[names.length-1]; var image = { FileId: fileId, Path: absolutePath, Name: name, UserId: User.getCurActiveUserId(), Title: name, Type: ext, Size: stat && stat.size, CreatedTime: new Date() } Images.insert(image, function(err, doc) { log(err); if(err) { callback && callback(false); } else { callback && callback(doc); } }) }, addImageForce: function(fileId, path, callback) { var me = this; // 先删除之, 可能是本地有记录, 但是文件没了 Images.remove({FileId: fileId}, function() { me._addImage(fileId, path, callback); }); }, // 获取图片本地路径 getImageLocalPath: function(fileId, callback) { Images.findOne({FileId: fileId}, function(err, doc) { if(!err && doc && doc.Path) { // FileLocalPath是相对于项目的路径 callback(true, doc.Path); } else { callback(false, false); } }); } }; module.exports = File;