'How to make an API to return JSON text after uploading files with Angular/Node JS?

My goal is to create a File Select interface in order to upload files on a server using Angular CLI and Node JS.
I built an API with Node JS that must check the type of the file (only CSV files) and then return a JSON text saying whether the upload succeeds or fails. I decided to give it a try with Multer (see https://www.npmjs.com/package/multer).
Everything is working and my CSV is well uploaded. But I don't manage to get the JSON message from the API after a user uploads his file.

Here is the files I created :

HTML PART

  <div class="file-upload">
    <input type="file"  name="file" ng2FileSelect [uploader]="uploader" accept="text/csv" />
    <button type="button" class="btn btn-primary btn-sm" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
      RUN
    </button>
  </div>

TS PART

const URL = 'https://xxxxx.com:xxxx/upload';
export class SelectFileComponent implements OnInit {
  public uploader: FileUploader = new FileUploader({
    url: URL,
    itemAlias: 'fileToUpload',
  });
  constructor() { }

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };
    this.uploader.onCompleteItem = (item: any, status: any) => {
    };
  }

NODE JS PART

// File upload settings  
const PATH = './uploads';
let storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, PATH);
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname)
  }
});


let upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype == 'application/vnd.ms-excel'){
      cb(null, true);
    } else {
      cb(null, false);
      return cb('Only csv format allowed!');
    }
  }
});

// Post file
   app.post('/upload', upload.single('fileToUpload'), async (req, res) => {
  // I would like to do :
  // if file has not csv extension...
     {
     return res.json({
     success: false,
     message: "Bad format, please select a CSV file",
      });
  } 
  // else if everything is ok... 
    {
     return res.json({
     success: true,
     message: "Some success message"
     });
  }
  else {}
});

It seems I can't use a variable created in the "File upload settings" into the "Post file" part.
Have you any ideas to help me to implement that JSON message ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source