Upload a file to Lumen API from Angular2 app

Solution:

Try the following.

Template:

<input type="file" 
        id="file"
        (change)="onInputFile($event)">

Code:

onInputFile(event){
    let file = event.target.files[0];

    uploadFile(file).then(
       (res:any) => { console.log(res);},
       (error:any) => { console.log(error);}
    )
}

uploadFile(file, url) {
    return new Promise((success, reject) => {
        let formData = new FormData();
        formData.append('myFile', file);

        let xhr = new XMLHttpRequest();

        xhr.onload = function(){
            if(this.status == 200){
                success(this.response);
            } else {
                reject(this.statusText);
            }
        }

        xhr.onerror = function(){
            reject(this.statusText);
        }

        xhr.open('POST', url, true);
        xhr.send(formData);
    });
}

Hope it would help.

UPDATE:

there is a “angular-way” to do it with the http-class…

Angular2 documentation say: the POST body must actually be a string. You can try convert a file to base64 and post it.

uploadFile(file, url){
        let req = this.http;
        let reader = new FileReader();

        reader.readAsDataURL(file);

        reader.onload = function() {
            req.post(url, reader.result).toPromise();
        };

        reader.onerror = function(error) {
            console.log('Error: ', error);
        };   
    }