Use Promise when uploading files in Angular and Node.js

Asked

Viewed 153 times

1

Good afternoon guys, I am with a registration form in homologation, but when I upload an image and a pdf file in the first moment my request returns that I have not filled all the data, but then this request returns that the user was registered.

I understood that this is due to my function to be asynchronous, but I’m 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 In the Back-End:

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 I implement the laws ?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.