[英]How to make Angular2 Http upload a file ?
以下尝试从Angular2应用程序发送文件的尝试总是以REST API结尾,无法识别请求中的文件。 (即使内容接缝在那里!)
在花了几个小时搜索StackOverflow和无数其他在线资源之后,我得出的结论是,最新版本的Angular2 Http模块/服务现在应该能够处理文件上传。 (过去无法做到这一点真是太神奇了!)
Component.html
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" novalidate> <label>Votre avatar !</label> <input class="form-control" type="file" name="avatar" (change)="imageUpload($event)" >
Component.ts
imageUpload(e) { let reader = new FileReader(); //get the selected file from event let file = e.target.files[0]; reader.onloadend = () => { this.image = reader.result; } reader.readAsDataURL(file); } onSubmit() { if (this.image){ this.authService.setAvatar(this.image).subscribe( d => { //Do Nothing... Will navigate to this.router.url anyway so... }, err =>{ this.errorMessage = err; console.log(err); } ); } }
authService.ts
setAvatar(image:any){ let form: FormData = new FormData(); form.append('avatar', image); return this.http.post (Config.REST_URL + 'user/setAvatar?token=' +localStorage.getItem('token'), form, {headers: new Headers({'X-Requested-With': 'XMLHttpRequest' })} ).catch(this.handleError); }
REST_API Php(LARAVEL)
public function setAvatar(Request $request){ if($request->hasFile("avatar")) { // ALWAYS FALSE !!!! $avatar = $request->file("avatar"); $filename = time() . "." . $avatar->getClientOriginalExtension(); Image::make($avatar)->fit(300)->save(public_path("/uploads/avatars/" . $filename)); return response()->json(['message' => "Avatar added !"], 200); } return response()->json(['message' => "Error_setAvatar: No file provided !"], 200); }
请求有效负载的内容(从Chrome Inspect /网络中可以看到)
------WebKitFormBoundary8BxyBbDYFTYpOyDP Content-Disposition: form-data; name="avatar"
应该更像是...:
Content-Disposition: form-data; name="avatar"; filename="vlc926.png" Content-Type: image/png
原来Angular2的Http现在可以发送文件了……而且非常容易!....我简直不敢相信那里没有文档可以显示这个信息! 除了这个。 (归功于MICHACr DYMEL)
https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/
HTML
<input #fileInput type="file"/> <button (click)="addFile()">Add</button>
Component.ts
@ViewChild("fileInput") fileInput;
addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
this.uploadService
.upload(fileToUpload)
.subscribe(res => {
console.log(res);
});
}
}
服务
upload(fileToUpload: any) {
let input = new FormData();
input.append("file", fileToUpload);
return this.http.post("/api/uploadFile", input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.