File Upload In Angular?

前端 未结 14 2335
执念已碎
执念已碎 2020-11-22 08:10

I know this is very a general question but I am failing to upload a file in Angular 2. I have tried

1) http://valor-software.com/ng2-file-upload/ and

2) h

14条回答
  •  难免孤独
    2020-11-22 08:53

    Since the code sample is a bit outdated I thought I'd share a more recent approach, using Angular 4.3 and the new(er) HttpClient API, @angular/common/http

    export class FileUpload {
    
    @ViewChild('selectedFile') selectedFileEl;
    
    uploadFile() {
    let params = new HttpParams();
    
    let formData = new FormData();
    formData.append('upload', this.selectedFileEl.nativeElement.files[0])
    
    const options = {
        headers: new HttpHeaders().set('Authorization', this.loopBackAuth.accessTokenId),
        params: params,
        reportProgress: true,
        withCredentials: true,
    }
    
    this.http.post('http://localhost:3000/api/FileUploads/fileupload', formData, options)
    .subscribe(
        data => {
            console.log("Subscribe data", data);
        },
        (err: HttpErrorResponse) => {
            console.log(err.message, JSON.parse(err.error).error.message);
        }
    )
    .add(() => this.uploadBtn.nativeElement.disabled = false);//teardown
    }
    

提交回复
热议问题