Angular 2 - 带输入文件的模型驱动表单(文件上传) [英] Angular 2 - Model driven form with input file (file upload)

查看:97
本文介绍了Angular 2 - 带输入文件的模型驱动表单(文件上传)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently developing in Angular 2 a form that allows a user to update his profile: email and password.

user-edit.component.html:

user-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>

user-edit.component.ts:

user-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:

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

今天我想允许上传一张照片添加文件类型字段。

Today I want to allow uploading of a photo by simply adding a file type field.

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

But I found very little information on the subject.

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

The only solution seems to approach what I want to do is here: https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/

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

Is there a better solution to achieve this? A solution that is closer to my code because I want maximum standardization? For example with the $http Angular service I already use?

谢谢!

推荐答案

文件在angular2中上传,

File Uploading in angular2,

事实上, Http 类不支持时刻。

In fact, the Http class doesn't support that at the moment.

您需要利用基础XHR对象来做到这一点:

You need to leverage the underlying XHR object to do that:

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

See this plunkr for more details: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info.

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

There is a an issue and a pending PR regarding this in the Angular repo:

  • https://github.com/angular/http/issues/69
  • https://github.com/angular/angular/pull/7310/files

回答从这里开始

这篇关于Angular 2 - 带输入文件的模型驱动表单(文件上传)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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