다음 코드는 Angular2 앱에서 파일을 보내려고합니다. REST API에서는 항상 수신중인 요청에서 파일을 인식 할 수 없게됩니다. (콘텐츠 솔기가있을지라도!)Angular2 Http를 대체하여 파일을 업로드하는 방법은 무엇입니까?
StackOverflow 및 수많은 온라인 소스를 검색하는 데 소비 한 시간이 지나면 Angular2 Http 모듈/서비스의 최신 버전이 이제 파일 업로드를 처리 할 수 있어야한다는 결론에 도달했습니다. . (과거에 그렇게 할 수 없다는 사실은 놀랍습니다!) 이 article 또는 this git sample을 참조하십시오.
ng2-file-upload와 같은 외부 라이브러리를 사용하려면 Angular2 :: Http를 가능한 한 적은 수정으로 다음 코드로 대체 할 수 있어야합니다. (즉, I는 HTML 형식을 변경할 수 없다.)
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 빌 (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);
}
내용 (크롬에서 보듯이 검사/네트워크)
------WebKitFormBoundary8BxyBbDYFTYpOyDP
Content-Disposition: form-data; name="avatar"
은 ... 비슷한 제품을 더해야합니다
Content-Disposition: form-data; name="avatar"; filename="vlc926.png"
Content-Type: image/png
_ "이 기사를 참조하십시오"_이 기사는 귀하가 답변에 링크 한 것과 정확히 같은 해결책을 보여줍니다. – zeroflagL
링크가 없습니다 ... "이 문서보기"! – Tuthmosis