Angular 2 - 带输入文件的模型驱动表单(文件上传)

时间:2016-04-03 08:38:29

标签: javascript angularjs angular

我目前正在Angular 2中开发一个允许用户更新其个人资料的表单:电子邮件和密码。

用户edit.component.html:

<form novalidate="novalidate" [ngFormModel]="form" (ngSubmit)="form.valid && onSubmit()">
    <fieldset>
        <div>
            <label for="email">
                Email
            </label>

            <input id="email" type="email" #email="ngForm" ngControl="email"/>

            <div class="error" *ngIf="email.control.hasError('required') && email.touched">
                This value is required.
            </div>
        </div>

        <div>
            <label for="password">
                Password
            </label>

            <input id="password" type="password" #password="ngForm" ngControl="password"/>

            <div class="error" *ngIf="password.control.hasError('required') && password.touched">
                This value is required.
            </div>
        </div>
    </fieldset>

    <button type="submit" [disabled]="!form.valid">
        Save
    </button>
</form>

用户edit.component.ts:

@Component({
    selector: 'user-edit',
    templateUrl: 'app/components/user-edit/user-edit.component.html',
})
export class UserEditComponent implements OnInit {
    form: any;

    errors = [];

    constructor(
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _userService: UserService
    ) {}

    ngOnInit() {
        this.form = this._formBuilder.group({
            'email': ['', Validators.required)],
            'password': ['', Validators.required],
        });
    }

    onSubmit() {
        var self = this;

        this._userService.edit(this.form.value, function (response: Response) {
            console.log('OK');
        }, function (response: Response) {
            console.log('ERROR');
        });
    }
}

user.service.ts:

@Injectable()
export class UserService {
    constructor (
        private _http: Http
    ) {}

    edit(user: User, cfOnNext?: Function, cfOnError?: Function): void {
        let body = JSON.stringify(user);
        let headers = new Headers({
            'Content-Type': 'application/json',
        });
        let options = new RequestOptions({
            headers: headers,
        });

        self._http.put('https://api.dom/me', body, options).subscribe(function (response) {
            if (cfOnNext) {
                cfOnNext(response);
            }
        }, function (response) {
            if (cfOnError) {
                cfOnError(response);
            }
        });
    }
}

今天我想通过简单地添加文件类型字段来允许上传照片。

但我发现关于这个问题的信息很少。

唯一的解决方案似乎接近我想要做的是: https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/

有没有更好的解决方案来实现这一目标?一个更接近我的代码的解决方案,因为我想要最大程度的标准化?例如,我已使用$ http Angular服务?

谢谢!

1 个答案:

答案 0 :(得分:2)

文件在angular2中上传,

事实上,Http类目前不支持此类。

您需要利用基础XHR对象来执行此操作:

import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class UploadService {
  constructor () {
    this.progress$ = Observable.create(observer => {
      this.progressObserver = observer
    }).share();
  }

  private makeFileRequest (url: string, params: string[], files: File[]): Observable {
    return Observable.create(observer => {
      let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();

      for (let i = 0; i < files.length; i++) {
        formData.append("uploads[]", files[i], files[i].name);
      }

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next(JSON.parse(xhr.response));
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event) => {
        this.progress = Math.round(event.loaded / event.total * 100);

        this.progressObserver.next(this.progress);
      };

      xhr.open('POST', url, true);
      xhr.send(formData);
    });
  }
}

有关详细信息,请参阅此plunkr:https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info

在Angular回购中有一个问题和待处理的PR:

回答from here