I have a question while making the avatar image(url) in user sign up form on my project.
frontend: react.js backend: nest.js
First of all, I saved my avatar image in server folder with using multer. and then i want to get avatar image to my frontend but i have no idea about next step.
code is below..
main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as session from 'express-session';
import * as express from 'express';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.enableCors({
origin: true,
credentials: true,
});
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
secure: false,
},
}),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
app.use('/avatar', express.static(join(__dirname, '../avatar')));
await app.listen(5000);
}
bootstrap();
sign up code (Controller)
@Post('signup')
@UseInterceptors(
FileInterceptor('avatar', {
storage: diskStorage({
destination: Helper.destinationPath,
filename: Helper.customFileName,
}),
}),
)
async postSignUpData(
@UploadedFile() file: Express.Multer.File,
@Body()
body: UserSignDataDto,
@Res() res: Response,
) {
//
if (file !== null) {
body.avatar = file;
}
//
try {
const result = await this.userService.signUpUserData(body);
return res.status(200).json({
message: 'Create new Account!',
data: result,
});
} catch (error) {
return res.status(400).json({
message: error.message,
});
}
}
sign up service logic
@Injectable()
export class UsersService {
constructor(
@InjectModel('UserData') private userModel: Model<UserDocument>,
) {}
//
async signUpUserData(signUpData: UserSignDataDto) {
//
const { userId, pass1, pass2, email, nickname, avatar } = signUpData;
const checkExists: boolean = await this.userModel.exists({
$or: [{ userId }, { email }, { nickname }],
});
if (checkExists) {
throw new Error(`This user id or email or nickname is already taken.`);
}
if (pass1 !== pass2) {
throw new Error(`Password does not match`);
}
const user = new this.userModel({
userId,
password: pass2,
email,
nickname,
avatarUrl: avatar ? avatar.path : 'Not Avatar',
});
return await user.save();
}
How can I front load the saved avatar image from avatar folder..
Please let me know if you have a suitable example.
Thank you all