Angular2 ExpressJs-文件上传到服务器 [英] Angular2 ExpressJs - File upload to the server

查看:61
本文介绍了Angular2 ExpressJs-文件上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

Component.ts

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

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

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

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.

推荐答案

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

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

服务器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:

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

这篇关于Angular2 ExpressJs-文件上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆