用于文件上传的Angular2服务器端侦听器

时间:2016-07-19 11:49:18

标签: javascript node.js typescript angular vaadin

在Angular2 CLI项目中,我最终实现了Vaadin的this上传按钮。按钮用户界面有效,但我不知道如何实际上传文件任何地方

我一直在寻找关于快速服务器的解决方案来监听文件上传, multer 节点服务器,我真的不知道如何写这样的服务器,把它放在哪里,如何启动它,如何访问它等等。我认为像文件上传这样简单的东西应该更容易实现,但似乎不是。

什么是简单的解决方案,以便在Angular2旁边实现,以便按钮实际上传文件到某处,以便我可以在以后下载它们?

1 个答案:

答案 0 :(得分:8)

ng2-uploader repo中找到解决方案并适应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);
});

对于那些需要在启动this is an awesome solution运行的server.js测试和工作的人来说,这是一个奖励。