如何使用angularjs2

时间:2016-09-27 17:38:46

标签: angular multipart

angular2支持多部分表单提交,任何可用的示例吗?

非常感谢任何特定于此文档的链接

请参阅angular github https://github.com/angular/angular/issues/6030

的帖子

****稍后使用XMLHttpRequest ****

更新了工作演示

展示FormData作为http

的一部分发送http的任何示例

下面的草稿代码对我来说很好,但想知道 <input id="single_f_fileup" [(ngModel)]="model.image" type="file" (change)="selectFile($event)" name="single_fileup" /> 是否支持

HTML

selectFile($event): void {
 var files = $event.target.files || $event.srcElement.files;
        var file = files[0];
        let formData = new FormData();
        formData.append("single_fileup", file);
        formData.append('key1', 'value1');
        formData.append('key2', 'value2');
       var req = new XMLHttpRequest();
       req.open("POST", "/api/fileupload");
       req.send(formData);
}

ANGULAR2

var multer  = require('multer');
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
  router.post('/api/fileupload', upload.single('single_fileup'), function(req, res, next){
        console.log(req.body,req.file);
});

NODEJS 6.2

 this.http.post('/api/fileupload', formData)
            .map(this.extractData)
            .catch(this.handleError);

如何使下面的代码工作?

display:inline-block

2 个答案:

答案 0 :(得分:13)

传递包含图像

的formData的示例代码段

https://gist.github.com/arciisine/ee57727e56cbc5e83739b2c24fd69658

https://github.com/angular/angular/issues/6030

import { Component, Input, AfterViewInit } from '@angular/core';
import { NgModel, DefaultValueAccessor, NgControl } from '@angular/forms';
import { Http, Headers, RequestOptions } from '@angular/http';

@Component({
  selector: 'app-file-uploader',
  template: '<input type="file" (change)="updated($event);">',
  providers: [NgModel, DefaultValueAccessor]
})
export class FileUploaderComponent implements AfterViewInit {

  static ROOT = '/rest/asset';

  @Input() private companyId: string = '';
  private value: string;
  private changeListener: Function;

  constructor(private http: Http, private input: NgControl) {
    this.input.valueAccessor = this;
  }

  ngAfterViewInit() {
  }

  writeValue(obj: any): void {
    this.value = obj;
  }

  registerOnChange(fn: any): void {
    this.changeListener = fn;
  }

  registerOnTouched(fn: any): void {

  }

  updated($event) {
    const files = $event.target.files || $event.srcElement.files;
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file);

    const headers = new Headers({});
    let options = new RequestOptions({ headers });
    let url = FileUploaderComponent.ROOT + (this.companyId ? '/' + this.companyId : '');

    this.http.post(url, formData, options).subscribe(res => {
      let body = res.json();
      this.value = body.filename;

      if (this.changeListener) {
        this.changeListener(this.value);
      }
    });
  }
}

答案 1 :(得分:4)

ng2-file-upload将成为您分段上传的指南。如果你想查看指令,AngularJs也有ng-file-upload