Cris Cris - 1 year ago 142
Node.js Question

Angular2 server-side-listener for file uploads

In an Angular2 CLI project, i finnaly implemented this upload button from Vaadin. The button UI works, but i don't know how to actually make it upload a file anywhere.

I keep finding solutions about express server that listens for file uploads, multer or node server, and i really have no idea how to write such a server, where to put it, how to start it, how to access it, etc.. I figured that something as trivial as file upload should be easier to achieve, but it seems is not.

What is a simple solution to implement along side Angular2 in order make the button actually upload files somewhere so i can download them later?

Answer Source

Found the solution in ng2-uploader repo and adapted to work with Vaadin Upload.


    <div *ngIf="newName.valid">


'use strict';

const Hapi        = require('hapi');
const Inert       = require('inert');
const Md5         = require('md5');
const Multiparty  = require('multiparty');
const fs          = require('fs');
const path        = require('path');
const server      = new Hapi.Server();

server.connection({ port: 10050, routes: { cors: true } });
server.register(Inert, (err) => {});

const upload = {
  payload: {
    maxBytes: 209715200,
    output: 'stream',
    parse: false
  handler: (request, reply) => {
    const form = new Multiparty.Form();
    form.parse(request.payload, (err, fields, files) => {
      if (err) {
        return reply({status: false, msg: err});

      let responseData = [];

      files.file.forEach((file) => {
        let fileData = fs.readFileSync(file.path);

        const originalName = file.originalFilename;

        const generatedName = Md5(new Date().toString() + 
          originalName) + path.extname(originalName);

        const filePath = path.resolve(__dirname, 'uploads', 

        fs.writeFileSync(filePath, fileData);
        const data = {
          originalName: originalName,
          generatedName: generatedName


      reply({status: true, data: responseData});

const uploads = {
  handler: {
    directory: {
      path: path.resolve(__dirname, 'uploads')

  { method: 'POST', path: '/upload',          config: upload  },
  { method: 'GET',  path: '/uploads/{path*}', config: uploads }

server.start(() => {
  console.log('Upload server running at',;

And a bonus for those who need server.js running at startup this is an awesome solution tested and working.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download