gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:57:56 24 4
gpt4 key购买 nike

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

用户编辑.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>

用户编辑.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');
});
}
}

用户服务.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 服务?

谢谢!

最佳答案

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

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

在 Angular 仓库中有一个问题和一个待处理的 PR:

回答from here

关于javascript - Angular 2 - 带有输入文件的模型驱动表单(文件上传),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36383297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com