angularfile-uploadlaravel-5.3angular-file-upload

Need Help! Angular 2 File/Image upload via API


I'm stack around uploading image/file using Angular2. I don't like to add any plugins to upload file in angular2. Is there any simple way to upload image via API using Angular2 without any third party extension ?

NB: i am using laravel as server


Solution

    1. The Template

    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
    <button type="button" (click)="upload()">Upload</button>

    1. The Service

    export class FileUpload{
    /* This method will worked for single file upload, if you need multipule file upload then replace formData.append("uploads", files[i], files[i].name); to formData.append("uploads[]", files[i], files[i].name);
    */
    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
            return new Promise((resolve, reject) => {
                var formData: any = new FormData();
                var xhr = new XMLHttpRequest();
                for(var i = 0; i < files.length; i++) {
                    formData.append("uploads", files[i], files[i].name);
                }
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            resolve(JSON.parse(xhr.response));
                        } else {
                            reject(xhr.response);
                        }
                    }
                }
                xhr.open("POST", url, true);
                xhr.send(formData);
            });
        }
    }

    1. The Component

    export class AppComponent {
      filesToUpload: Array<File>;
    
      constructor(private _fileUpload:FileUpload) {
            this.filesToUpload = [];
      }
    
      upload() {
            this._fileUpload.makeFileRequest("/api/admin/upload-slider-image", [], this.filesToUpload).then((result) => {
                console.log(result);
            }, (error) => {
                console.error(error);
            });
        }
    
        fileChangeEvent(fileInput: any){
            this.filesToUpload = <Array<File>> fileInput.target.files;
        }
     }