Upload file to Lumen API from Angular2 application

I have an API (Lumen) that expects a file field in the body.

In Postman, I can just parse the file in the API, and Lumen will save it to the server.

But how to upload a file to the API using Angular2? I am currently using HTTP to execute post requests.

this.http.post(ENDPOINT, body, options).....
+4
source share
2 answers

Try the following.

Template:

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

the 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 this helps.

UPDATE:

there is "angular -way" to do this with the http-class ...

Angular2 Documentation says: POST authority should actually be a string. You can try to convert the file to base64 and publish 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);
        };   
    }
+2
source

Source: https://habr.com/ru/post/1653825/


All Articles