express.js每个用户的唯一目录

我有一个express.js 应用程序 ,我正在使用干墙来pipe理用户系统。

当用户注册时,我需要为该用户生成一个目录,并且我希望该用户能够将file upload到该目录并通过他或她的帐户查看这些文件。

我不完全确定,但我认为最有可能的目录生成,我将不得不这样做在views / signup / index.js,并且用户只能上传文件到他或她的目录,如果login。

不过,在保存和显示文件方面,我有点卡住了。 我几乎没有使用服务器端代码的经验,所以实现访问文件等操作稍微超出了我的范围。

在此先感谢那些帮助。

所以首先你应该使用fs.mkdir为每个用户创build一个文件夹:

http://nodejs.org/api/fs.html#fs_fs_mkdir_path_mode_callback

比方说,你想创build这些文件夹到你的应用程序的根/图像:

例:

 var fs = require('fs'); fs.mkdir(__dirname + '/images/' + userId, function(err) { if (err) { /* log err etc */ } else { /* folder creation succeeded */ } }); 

您应该使用userId作为文件夹名称(因为它比从用户名本身去除坏字符更容易,而且如果用户更改他的用户名,将来也可以使用)。

你需要做的第二件事是允许用户上传文件(但只有当他login并进入正确的文件夹)。 最好不要包含所有路由的bodyParser中间件,而是包含所有路由的json && urlencoded中间件( http://www.senchalabs.org/connect/json.html && http://www.senchalabs.org/ connect / urlencoded.html )和仅用于上传url的multipart中间件( http://www.senchalabs.org/connect/multipart.html &&示例: https : //github.com/visionmedia/express/blob/master/ examples / multipart / index.js )。

一个例子:

 app.post('/images', express.multipart({ uploadDir: '/tmp/uploads' }), function(req, res, next) { // at this point the file has been saved to the tmp path and we need to move // it to the user's folder fs.rename(req.files.image.path, __dirname + '/images/' + req.userId + '/' + req.files.image.name, function(err) { if (err) return next(err); res.send('Upload successful'); }); }); 

注意:在上面的例子中,我已经考虑到req.userId是通过auth中间件来填充用户的id。

如果用户有权查看图像,则将图像显示给用户(Auth中间件也应该应用于此path):

 app.get('/images/:user/:file', function(req, res, next) { var filePath = __dirname + '/images/' + req.userId + '/' + req.params.file; fs.exists(filePath, function(exists) { if (!exists) { return res.status(404).send('Not Found'); } // didn't attach 'error' handler here, but you should do that with streams always fs.createReadStream(filePath).pipe(res); }); }); 

注意:在生产中你可能想用send来代替,那个例子只是演示stream( https://github.com/visionmedia/send )。