Good afternoon guys, I have a registration form in homologation, but when I upload an image and a pdf file at first my request returns me that I did not fill in all the data, but then this request returns me that the user has been registered.
I understand that this is because my function is asynchronous, however I am not understanding how to validate this with a promise.
follow the code of how far I've come:
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Base64Service } from '../../services/base64.service';
import { HttpClient } from '@angular/common/http';
import { FileUploader, FileItem } from 'ng2-file-upload/ng2-file-upload';
import { environment } from '../../../environments/environment';
import { DomSanitizer } from '@angular/platform-browser';
import { Student } from '../../models/student';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
form = {
cpf: '',
picture: FileItem.prototype,
resume: FileItem.prototype,
name: '',
email: '',
description: '',
linkedin: '',
group: '',
isWorking: false,
jobPosition: '',
birthDate: ''
};
resume;
resumeName;
validResume: boolean = true;
isRequired: boolean = false;
studentCreated: boolean = false;
picture;
pictureName = "Escolha uma Foto";
validPicture: boolean = true;
updateStudent: boolean = false;
showForbiddenError: boolean = false;
showJobPosition: boolean = false;
public uploader: FileUploader = new FileUploader({ url: environment.apiUrl + "uploadfile", itemAlias: 'studentfile' });
constructor(private base64: Base64Service, private http: HttpClient, private router: Router, private sanitizer: DomSanitizer) { }
ngOnInit() {
this.uploader.onAfterAddingFile = (file) => {
if (file.file.type.startsWith("image/") && file.file.size < 2097152) {
file.index = 0;
this.form.picture = file;
this.replaceInQueue(file);
} else if ((file.file.type == 'application/msword' || file.file.type == 'application/pdf') && file.file.size < 2097152) {
file.index = 1;
this.form.resume = file;
this.replaceInQueue(file);
} else if (this.uploader.queue.length > 2) {
this.uploader.clearQueue();
this.clearImage();
this.clearResume();
alert("Ocorreu um erro. Faça o upload dos arquivos novamente.")
} else {
this.uploader.removeFromQueue(file);
}
file.withCredentials = false;
};
this.uploader.onCompleteItem = (item: any, response: any, status: any) => {
let res = JSON.parse(response);
if (res.type.startsWith("image/")) {
this.form.picture = res.path;
} else if (res.type.startsWith("application/")) {
this.form.resume = res.path;
} else {
console.log(status);
this.showForbiddenError = true;
}
};
this.uploader.onCompleteAll = () => {
if (this.updateStudent) {
this.putStudent();
} else {
this.postStudent();
}
};
}
replaceInQueue(file) {
let foundIndex = this.uploader.queue.findIndex(e => e.index == file.index);
if (file != this.uploader.queue[foundIndex]) {
this.uploader.queue.splice(foundIndex, 1);
}
this.uploader.addToQueue(file);
}
uploadImage($event) {
let file = $event.target.files[0];
if (file.type.startsWith('image/') && file.size < 2097152) {
this.base64.convert($event).then(response => {
this.pictureName = file.name;
this.picture = this.sanitizer.bypassSecurityTrustUrl('data: image/jpg;base64, ' + response);
this.validPicture = true;
})
} else {
this.clearImage();
}
}
clearImage() {
this.pictureName = "Escolha uma foto";
this.picture = null;
this.validPicture = false;
}
uploadResume($event) {
let file = $event.target.files[0];
if ((file.type == 'application/msword' || file.type == 'application/pdf') && file.size < 2097152) {
let blob = new Blob([file], { type: file.type });
this.resume = blob;
this.resumeName = file.name;
this.validResume = true;
} else {
this.clearResume();
}
}
And No Backend:
const express = require('express');
const Student = require('../models/student');
const router = new express.Router();
const multer = require('multer');
const fs = require('fs');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
if (file.mimetype.startsWith('image/')) {
cb(null, './public/images/');
} else {
cb(null, './public/docs/');
}
},
filename: function (req, file, cb) {
let savedFile = file.originalname + '-' + Date.now();
cb(null, savedFile);
}
})
var upload = multer({ storage: storage });
router.get('/getfile/public/:type/:path', (req,res) => {
let type = req.params.type + '/';
let path = req.params.path;
fs.readFile(__dirname + '/../public/'+ type + path,
(err, data) => {
if (err) {
res.status(500).send({message: "Erro ao encontrar arquivo."});
} else {
let b64 = data.toString("base64");
let contentType = "application/pdf"
if (type == "images") {
contentType = "image/jpg"
}
res.writeHead(200, {
'Content-Type': contentType,
'Content-Length': b64.length
});
res.end(b64);
}
});
});
router.post('/uploadfile', upload.single('studentfile'), (req,res) => {
if (req.file) {
res.status(200).send({ path: req.file.path, type: req.file.mimetype });
} else {
res.status(500).send({message: 'Erro no upload de arquivo!'})
}
});
//Criar um novo aluno
router.post('/student', (req, res) => {
let student = new Student(req.body);
let err = student.validateSync();
if (err) {
return res.status(400).send(err);
} else {
student.save((err) => {
if (err) {
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate email || cpf
return res.status(400).send({message: 'Usuario existente!'});
}
console.error(err);
return res.status(500).send({message: 'Erro de servidor'});
}
return res.status(201).send(student);
})
}
});
Can anyone help me understand how to implement promises?