2017-04-18 38 views
0

以下嘗試從Angular2應用程序發送文件始終在REST API中無法識別請求中的文件。 (即使內容接縫在那裏!)如何讓Angular2 Http上傳文件?

花費數小時搜索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); 
 
    }

內容(如從鉻看出檢查/網絡)

------WebKitFormBoundary8BxyBbDYFTYpOyDP 
 
Content-Disposition: form-data; name="avatar"

應該更像...:

Content-Disposition: form-data; name="avatar"; filename="vlc926.png" 
 
Content-Type: image/png

+0

你可以嘗試使用ng2-file-upload。爲我工作很好。 –

回答

2

原來Angular2的HTTP現在可以發送文件...它的超級容易....我!只是不能相信有沒有文件顯示這個! Except this one. (Credits to MICHAŁ 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); 
     }); 
    } 
} 

的service.ts

upload(fileToUpload: any) { 
    let input = new FormData(); 
    input.append("file", fileToUpload); 

    return this.http.post("/api/uploadFile", input); 
} 
+1

請不要張貼僅鏈接的答案。這些鏈接往往會打破,並使答案無用。相反,將相關信息提供給您的答案。 – ceejayoz

+1

我做了...希望這有助於其他人! – Tuthmosis