MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Angular2 ExpressJs - Caricamento di file sul server

Stavo cercando di fare la stessa cosa ed ecco la mia soluzione (non sono sicuro che questo sia il modo migliore per farlo),

server js:

var formidable = require('formidable');
var fs = require('fs');

app.post('/upload', function(req, res){

  var form = new formidable.IncomingForm();

  form.multiples = false;

  form.uploadDir = path.join(__dirname, '/public/uploads');


  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  form.on('end', function() {
    res.end('success');
  });

  form.parse(req);

});

componente.app:

import { Component, OnInit, NgZone } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: 'js/app/app.component.html'
})
export class AppComponent {
   filesToUpload: Array<File>;

    constructor() {
        this.filesToUpload = [];
    }

    upload() {
        this.makeFileRequest("http://localhost:3000/upload", [], this.filesToUpload).then((result) => {
            console.log(result);
        }, (error) => {
            console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
           var formData: any = new FormData();
            var xhr = new XMLHttpRequest();

            for(var i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }

            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }

}

}

Nota:questo sta usando formidabile e non multer