|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | +import mkdirp from 'mkdirp'; |
1 | 4 | import assign from 'object-assign'; |
2 | 5 | import configs from '../../../configs/project/server'; |
3 | 6 | import Errors from '../../common/constants/Errors'; |
4 | | -import { handleDbError } from '../decorators/handleError'; |
| 7 | +import handleError, { handleDbError } from '../decorators/handleError'; |
5 | 8 | import User from '../models/User'; |
6 | 9 | import filterAttribute from '../utils/filterAttribute'; |
7 | 10 | import { loginUser } from '../../common/actions/userActions'; |
@@ -213,8 +216,19 @@ export default { |
213 | 216 | uploadAvatar(req, res) { |
214 | 217 | // use `req.file` to access the avatar file |
215 | 218 | // and use `req.body` to access other fileds |
216 | | - res.json({ |
217 | | - downloadURL: `/users/${req.user._id}/${req.file.filename}`, |
218 | | - }); |
| 219 | + let { filename } = req.files.avatar[0]; |
| 220 | + let tmpPath = req.files.avatar[0].path; |
| 221 | + let targetDir = path.join( |
| 222 | + __dirname, '../../public', 'users', req.user._id.toString() |
| 223 | + ); |
| 224 | + let targetPath = path.join(targetDir, filename); |
| 225 | + |
| 226 | + mkdirp(targetDir, handleError(res)(() => { |
| 227 | + fs.rename(tmpPath, targetPath, handleError(res)(() => { |
| 228 | + res.json({ |
| 229 | + downloadURL: `/users/${req.user._id}/${filename}`, |
| 230 | + }); |
| 231 | + })); |
| 232 | + })); |
219 | 233 | }, |
220 | 234 | }; |
0 commit comments