Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
Cristian Muscalu Avatar asked Jul 19 '16 11:07

Cristian Muscalu


1 Answers

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

component.html

    <div *ngIf="newName.valid">
            <vaadin-upload 
                    target="http://localhost:10050/upload"
            </vaadin-upload>
    </div>

server.js

'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', 
          originalName);

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

        responseData.push(data);
      });

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

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

server.route([
  { method: 'POST', path: '/upload',          config: upload  },
  { method: 'GET',  path: '/uploads/{path*}', config: uploads }
]);

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

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

like image 61
Cristian Muscalu Avatar answered Oct 02 '22 02:10

Cristian Muscalu