How to upload files in Angular with Laravel

How to upload files in Angular with Laravel

angular tutorials

 

angular tutorialsIn this post I will show you how to upload files in Angular 5 and send uploaded file to Laravel back-end. This tutorial assumes, you are already familiar with Angular and RXJS library. I will use REST API to send request from Angular front-end (client) to Laravel back-end (server). This is the first part (front-end part) of my file uploading tutorial. You can find the second part (back-end) of this tutorial from here

 
If you want to learn how to create a fresh Angular application, please read my previous post.
In this post followings you will learn,
 
  • Setup, file input-type in html.
 
  • Get uploaded file into the component.
 
  • Create a shared service to call http POST request.
 
  • Send file using http POST request.

Setup file input-type in html

First of all, we need to create a component. Open the command prompt in project folder and run “ng g c file-upload”.

create component

Create component

 

after create component

after create component

 Notice: This command updates our app.module.ts. So you don’t need to update it.
 
This is the new folder structure, after creating new file-upload component.

 

alter creating component

alter creating component

 
 
 Add this peace of code into our app.component.html
<app-file-upload></app-file-upload>

<router-outlet></router-outlet>

Then run our application using “ng serve –open”.

after creating component

after creating component

 

Add file input-type into our file-upload.component.html. After that, the file-upload.component.html file is as follows:

<label class="btn btn-primary upload-btn" style="background: #f3f3f3">
    Upload file<input type="file" name="file" hidden multiple (change)="uploadFile($event)">
</label>

Notice: Here i’m removed default file upload button and I customized. Also, you can change it as your choice. As an example:

file upload button

file upload button

Now, this the appearance of our application

after adding file upload button

after adding file upload button

 

Click on ‘Upload file’ text. It will pop up file selector dialog box.

file selector

file selector

Get uploaded file into the component

Now we have to create application logic. So, open file-upload.cpmponent.ts and add following code.

uploadFile(event){    //line 1
    let elem = event.target;  //line 2
    if(elem.files.length > 0){     //line 3
      let formData = new FormData();  //line 4
      formData.append('myfile', elem.files[0]);  //line 5
    }
}

Line 1: This function will be executed after click on ‘Upload file’ text.

Line 2: Assign target element to elem variable. The target element is file input-type.

Line 3: Make sure that the element has at least one file.

Line 4: Create formData object. It will help us to send selected file via http request.

Line 5: Append selected file as the value and ‘myfile’ as the key. This key will be used by in  back-end. Don’t worry. We will create back-end in the next tutorial.

Create a shared service to call http POST request

Then, we will create our shared service to send selected file with http POST request. Open command prompt and type ‘ng g s shared/services/file’.

create service

create service

This our folder structure, after creating the file-service

structure after creating service

structure after creating service

Then, open app.module.ts and add the following code. The app.module.ts file is as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http'; //line1
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FileUploadComponent } from './file-upload/file-upload.component';
import { FileService } from './shared/services/file.service'; //line2

@NgModule({
  declarations: [
    AppComponent,
    FileUploadComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule //line3
  ],
  providers: [ FileService ], //line4
  bootstrap: [AppComponent]
})
export class AppModule { }

Line1: import HttpClientModule.

Line2: import FileSerive.

Line3: add HttpClientModule into imports array.

Line4: add FileService into providers array.

Now time to, create our http request using HttpClient. The file.service.ts file is as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';  //line 1

@Injectable()
export class FileService {

  constructor(private httpClient: HttpClient) { } //line 2

  sendFile(formData: any){ //line 3
        //assume your backend base url is http://127.0.0.1:8000
  let baseUrl = ‘http://127.0.0.1:8000/api’; 
  	let url = `${baseUrl}/file`;       //line 4
  	return this.httpClient.post(   //line 5
  		url,
  		formData)
  }}

Line 1: import HttpClient

Line2: Inject HttpClient using constructor.

Line3: sendFile methods will be called by file uploadFile method in file.component.ts

Line4: REST-API url. This tutorial focus on client side. (See backend tutorial from here: link)

Line5: create the POST request and return response.

 Send the file using http POST request

Subscribe to our htpp POST request in fileUpload method in file-upload.component.ts

Notice: Post method in HttlClient, return an Observable. So, subscribing this Observable will send the POST request to specified url. Now, the file-upload.component.ts file as follows:

import { Component, OnInit } from '@angular/core';
import { FileService } from '../shared/services/file.service'; //line 6


@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit {

  constructor(private fileService: FileService ) { } line7

  ngOnInit() {
  }

  uploadFile(event){    //line 1
    let elem = event.target;  //line 2
    if(elem.files.length > 0){     //line 3
      let formData = new FormData();  //line 4
      formData.append('myfile', elem.files[0]);  //line 5

      this.fileService.sendFile(formData).subscribe( //line8
      	(response) => {
      		//response code
    console.log(response);
      	});

    }
elem.value = ""; //line 9
}
}

Line6: import file service into our file-upload.component.ts.

Line7: Inject file service using constructor

Line8: Subscribe observable.

Line9: Reset file upload element.

Now let me show you functionality until now.

As you can see file uploading working properly. There is a 404 not found error. It is because we didn’t specify ulr in back-end.  In the next tutorial we will create it. OK. That’s it.

Therefore, now you are ready to Upload files in Angular.

If you have any problem, please comment in the comment section. If you like this post don’t forget to share.

Find the project on github:Click here

Thank you for reading.

Summary
How to upload files in Angular with Laravel
Article Name
How to upload files in Angular with Laravel
Description
In this post I will show you how to upload files in Angular 5 and send uploaded file to Laravel back-end. This tutorial assumes, you are already familiar with Angular and RXJS library. I will use REST API to send request from Angular front-end (client) to Laravel back-end (server).
Author
Publisher Name
Angular + Laravel
Publisher Logo
Please follow and like us: