Angular2 listener server to download files

In the CLI Angular2 project, I finnaly implemented this download button from Vaadin. The button's user interface works, but I donโ€™t know how to get it to upload a file anywhere .

I continue to find solutions for an express server that listens for file downloads, a multer or node server , and I really have no idea how to write such a server, where to install it, how to start it, how to access it, etc. I realized that something as trivial as downloading files should be simpler, but it doesn't seem to be.

What is a simple solution to implement along the Angular2 side so that the button actually downloads the files somewhere so that I can upload them later?

+5
source share
1 answer

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

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 the bonus for those who need server.js running at startup is a terrific solution , tested and working.

+8
source

All Articles