Skip to content
This repository has been archived by the owner on Apr 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #668 from h-da/feature/611-Profile-Image-Resizing
Browse files Browse the repository at this point in the history
Feature/#611 user profile image resizing after upload to configured dimensions
  • Loading branch information
PatrickSkowronek authored Apr 23, 2018
2 parents 623face + 0d38c4b commit bab1760
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"migrate:inspect": "gulp migrate:inspect"
},
"dependencies": {
"@types/sharp": "^0.17.8",
"app-root-path": "^2.0.1",
"archiver": "^2.1.1",
"bcrypt": "^1.0.3",
Expand All @@ -53,6 +54,7 @@
"raven": "^2.5.0",
"reflect-metadata": "^0.1.12",
"routing-controllers": "^0.7.7",
"sharp": "^0.20.1",
"stream-buffers": "^3.0.1",
"to-utf-8": "^1.3.0",
"validator": "^9.4.1",
Expand Down
2 changes: 2 additions & 0 deletions api/src/config/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,6 @@ export default {
maxZipSize: 204800,

uploadFolder: process.env.UPLOADFOLDER || (appRoot + '/uploads/'),
maxProfileImageWidth: 512,
maxProfileImageHeight: 512,
};
19 changes: 15 additions & 4 deletions api/src/controllers/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {IUser} from '../../../shared/models/IUser';
import {IUserModel, User} from '../models/User';
import {isNullOrUndefined} from 'util';
import {errorCodes} from '../config/errorCodes';
import * as sharp from 'sharp';
import config from '../config/main';

const multer = require('multer');

Expand Down Expand Up @@ -311,19 +313,28 @@ export class UserController {
* @apiError BadRequestError
*/
@Post('/picture/:id')
addUserPicture(@UploadedFile('file', {options: uploadOptions}) file: any, @Param('id') id: string, @Body() data: any,
@CurrentUser() currentUser: IUser) {
addUserPicture(@UploadedFile('file', {options: uploadOptions}) file: any, @Param('id') id: string, @Body()
data: any, @CurrentUser() currentUser: IUser) {
return User.findById(id)
.then((user: IUserModel) => {
.then(async (user: IUserModel) => {
if (user.profile.picture && user.profile.picture.path && fs.existsSync(user.profile.picture.path)) {
fs.unlinkSync(user.profile.picture.path);
}

const resizedImageBuffer = await sharp(file.path)
.resize(config.maxProfileImageWidth, config.maxProfileImageHeight)
.withoutEnlargement(true)
.max()
.toBuffer({resolveWithObject: true});

fs.writeFileSync(file.path, resizedImageBuffer.data);

user.profile.picture = {
_id: null,
name: file.filename,
alias: file.originalname,
path: file.path,
size: file.size
size: resizedImageBuffer.info.size
};
return user.save();
})
Expand Down

0 comments on commit bab1760

Please sign in to comment.