Angular2 ExpressJs - 文件上传到服务器

时间:2016-06-11 07:36:48

标签: node.js mongodb express angular

Angular-2我正在尝试将文件上传到服务器。以下代码将文件上载到服务器,

如何链接到我的mongodb文档?上传文件时,我想将其链接到特定文档。

另外,我如何在UI中提供链接以从服务器下载上传的文件?

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

代码在服务器上创建一个uploads文件夹,并转储文件类型为.File的文件,这不是上传的实际.jpg文件。

1 个答案:

答案 0 :(得分:1)

我试图做同样的事情,这是我的解决方案(不确定这是否是最佳方式),

服务器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);
        });
    }

}

}

注意:这是使用强大而不是闷闷不乐的