var fs = require('fs');
var config = require('../config').config;

var mod = require('express/node_modules/connect/node_modules/formidable');
var upload_path = process.cwd() + '/public/user_data/images/';
mod.IncomingForm.UPLOAD_DIR = upload_path;

exports.upload_image = function(req,res,next){
	if(!req.session || !req.session.user){
		res.send('forbidden!');
		return;
	}

	var file = req.files.userfile;
	if(file){
		var name = file.name;
		var ext = name.substr(name.lastIndexOf('.'),4);
		var uid = req.session.user._id.toString();
		var time = new Date().getTime();
		var new_name = uid + time + ext;
		try{
			fs.realpathSync(upload_path + uid)
		}catch(err){
			fs.mkdirSync(upload_path + uid);
		}
		var new_path = upload_path + uid +'/' +new_name;
		fs.renameSync(file.path, new_path);
		var url = config.host + '/user_data/images/'+ uid + '/' +new_name;
		res.json({status:'success',url: url});
	}else{
		res.json({status:'failed'});
		return;
	}
};

@@ -13,24 +13,52 @@
 uire('fs');%0A
+var path = require('path');%0A
 var config =
@@ -86,16 +86,67 @@
 .config;
+%0Avar EventProxy = require('eventproxy').EventProxy;
 %0A%0Avar mo
@@ -485,232 +485,183 @@
 e;%0A%09
-if(file)%7B%0A%09%09var name = file.name;%0A%09%09var ext = name.substr(name.lastIndexOf('.'),4);%0A%09%09var uid = req.session.user._id.toString();%0A%09%09var time = new Date().getTime();%0A%09%09var new_name = uid + time + ext;%0A%09%09try
+// sould use async method%0A%09if(file)%7B%0A%09%09var proxy = new EventProxy();%0A%09%09function ensureDir()%7B%0A%09%09%09path.exists(upload_path + uid, function(exists)%7B%0A%09%09%09%09if(!exists)
 %7B%0A%09%09%09
+%09%09
 fs.
-realpathSync
+mkdir
 (upl
@@ -678,65 +678,192 @@
  uid
-)%0A%09%09%7Dcatch(err)%7B%0A%09%09%09fs.mkdirSync(upload_path + uid
+, function(err)%7B%0A%09%09%09%09%09%09if(err)%7B%0A%09%09%09%09%09%09%09return next(err);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09proxy.fire('ensureDir');%0A%09%09%09%09%09%7D)%0A%09%09%09%09%7Delse%7B%0A%09%09%09%09%09proxy.fire('ensureDir'
 );%0A%09%09
+%09%09
 %7D%0A
+%09%09%09%7D)%0A%09%09%7D%0A%09%09function moveImg()%7B%0A%09
 %09%09va
@@ -915,21 +915,18 @@
 ;%0A%09%09
-fs
+%09fd
 .rename
-Sync
 (fil
@@ -941,19 +941,77 @@
 new_path
-);%0A
+, function(err)%7B%0A%09%09%09%09if(err)%7B%0A%09%09%09%09%09return next(err);%0A%09%09%09%09%7D%0A%09%09
 %09%09var ur
@@ -1071,16 +1071,18 @@
 w_name;%0A
+%09%09
 %09%09res.js
@@ -1114,16 +1114,77 @@
  url%7D);%0A
+%09%09%09%7D)%0A%09%09%7D%0A%09%09proxy.once('ensureDir', moveImg);%0A%09%09ensureDir();%0A
 %09%7Delse%7B%0A

change to async