sql >> Database >  >> NoSQL >> MongoDB

Angular2 ExpressJs - Bestand uploaden naar de server

Ik probeerde hetzelfde te doen en hier is mijn oplossing (niet zeker of dit de beste manier is),

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);

});

app.component:

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);
        });
    }

}

}

Opmerking:dit is formidabel en niet multi




  1. hoe te controleren of een document is bijgewerkt of in MongoDB is ingevoegd

  2. Aggregeren op datum in Mongodb

  3. Kan externe mongodb-server niet verbinden met django/djongo

  4. Mongoose:pad voor validatiefout is vereist