user2180794
user2180794

Reputation: 1455

Angular2 ExpressJs - File upload to the server

Angular-2 I am trying to upload files to the server. The following code uploads the file to the server,

How can I link to my mongodb documents ? when A file is uploaded I want to link it to a specific document.

Also How can I provide a link in the UI to download the uploaded file from the server ?

Component.ts

@Component({
    selector: 'aptcontent',
    template: ` 
        <div> <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..."></div>

           <div >
                <a (click)="upload()">Upload Docs</a>
          </div>

    `,

    directives: [ROUTER_DIRECTIVES]
})

export class AptContentComponent implements OnInit {

    data: any;
    filesToUpload: Array<File>;

    constructor(private apartmentService: ApartmentService, private sharedService: SharedService, params: RouteParams) {
        this.filesToUpload = [];
    }


    ngOnInit() {}

    upload(){
      console.log('upload button clicked');

      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.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            }
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }
}    

Server.ts

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});


app.post("/upload", multer({dest: "./uploads/"}).array("uploads[]", 12), function(req, res) {});    

The code creates an uploads folder on the server and dumps the file with a file type as .File which is not the actual .jpg file uploaded.

Upvotes: 2

Views: 2615

Answers (1)

alexc
alexc

Reputation: 1310

I was trying to do the same thing and here is my solution (not sure if this is the best way to do it),

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

}

}

Note: This is using formidable and not multer

Upvotes: 1

Related Questions