5

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?

Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76
  • Well where do you plan to upload the files to? – tymeJV Jul 19 '16 at 12:46
  • Local disk, firebase, dropbox, anywhere the easyer the better. – Cristian Muscalu Jul 19 '16 at 13:56
  • well.. really the server side upload depends on what technology you are using on your server. Pick that first. – toskv Jul 19 '16 at 14:34
  • I am building using angular2CLI and for now i will be hosting the `dist` folder in a WAMP server on a pc. – Cristian Muscalu Jul 19 '16 at 14:42
  • If it's a WAMP server, then a PHP script will handle uploads. Your ng2 form will have to point to the PHP script that will handle uploaded files: the PHP script will usually check uploaded files have the right extension and weight, and move files from a temporary place on the server to a directory of your choice. See e.g. http://www.codingcage.com/2014/12/simple-file-uploading-with-php.html or http://www.tutorialspoint.com/php/php_file_uploading.htm – Manube Jul 23 '16 at 19:19
  • I was thinking to try php at your suggestion , but using it with Angular2 it's only going to bring pain. I will leave WAMP aside and learn how to host and use nodejs for hosting and server side. – Cristian Muscalu Jul 24 '16 at 10:51
  • [upload to dropbox using javascript](https://github.com/morrishopkins/DropBox-Uploader) – YaakovHatam Jul 26 '16 at 09:33

1 Answers1

8

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.

Community
  • 1
  • 1
Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76