File Upload with Angular2 to REST API

后端 未结 9 1091
萌比男神i
萌比男神i 2020-11-27 10:14

Actually, I\'m working on a Spring REST API with an interface coded in Angular 2.

My problem is I can\'t upload a file with Angular 2.

My Webresources in jav

9条回答
  •  臣服心动
    2020-11-27 10:52

    This is actually really easy to do in the final release. Took me a while to wrap my head around it because most information about it that I've come across is outdated. Posting my solution here in case anyone else is struggling with this.

    import { Component, ElementRef, Input, ViewChild } from '@angular/core';
    import { Http } from '@angular/http';
    
    @Component({
        selector: 'file-upload',
        template: ''
    })
    export class FileUploadComponent {
        @Input() multiple: boolean = false;
        @ViewChild('fileInput') inputEl: ElementRef;
    
        constructor(private http: Http) {}
    
        upload() {
            let inputEl: HTMLInputElement = this.inputEl.nativeElement;
            let fileCount: number = inputEl.files.length;
            let formData = new FormData();
            if (fileCount > 0) { // a file was selected
                for (let i = 0; i < fileCount; i++) {
                    formData.append('file[]', inputEl.files.item(i));
                }
                this.http
                    .post('http://your.upload.url', formData)
                    // do whatever you do...
                    // subscribe to observable to listen for response
            }
        }
    }
    

    Then just use it like so:

    
    

    That is really all there is to it.

    Alternatively, capture the event object and get the files from the srcElement. Not sure if any way is better than the other, to be honest!

    Keep in mind FormData is IE10+, so if you have to support IE9 you'll need a polyfill.

    Update 2017-01-07

    Updated code to be able to handle uploading of multiple files. Also my original answer was missing a rather crucial bit concerning FormData (since I moved the actual upload logic to a separate service in my own app I was handling it there).

提交回复
热议问题