Home » Angular » How to upload files in Angular with Laravel

How to upload files in Angular with Laravel

Nowadays, Angular and Laravel frameworks are popular web application development frameworks. In this tutorial, I will show you how to upload files in Angular 5 and send the uploaded file to the Laravel back-end. I assume that you are already familiar with the Angular and RXJS library. I will use REST full API yo send a request from Angular front-end (client) to Laravel back-end (server). This is the first part of the file uploading tutorial. You can find the second part of this tutorial from here

If you want to learn how to create a new Angular application, please read my previous post from here

In this tutorial, you will learn how to,

01. Setup file input-type in HTML.

02. Bring an uploaded file into a Angular component.

03. Create a shared service to call HTTP POST request.

04. Send a file via a HTTP POST request.

01. Setup file input-type in HTML

First of all, we need to create a component. So, 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 your app.module.ts. So, you don’t need to update it manually. 
 
This is the new folder structure, after creating the file-upload component.
alter creating component

alter creating component

 
 
 Add this piece of code into your app.component.html
<app-file-upload></app-file-upload>

<router-outlet></router-outlet>

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

after creating component

after creating component

After that, add the file input-type into your file-upload.component.html 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 removed default html file upload button and I customized. Also, you can change it as your choice. For and example:

file upload button

file upload button

So, this the look of our application.

after adding file upload button

after adding file upload button

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

file selector

file selector

02. Get uploaded file into the component

Then, we have to create application logic. So, open file-upload.cpmponent.ts and add the 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 when click on ‘Upload file’ text.

Line 2: Assign target element to elem variable. The target element is the 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 the selected file via http request.

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

03. Create a shared service to call http POST request

Then, I will create a shared service to send selected file via a http POST request. Open the command prompt and type ‘ng g s shared/services/file’.

create service

create service

This is our folder structure, after creating the file-service

structure after creating service

structure after creating service

Then, open the app.module.ts and add the following code. 

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 the HttpClientModule.

Line2: Import the FileSerive.

Line3: Add HttpClientModule into the imports array.

Line4: Add the FileService into the providers array.

Now time to create the http request by using HttpClient. After creating the http request, the code in 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 the HttpClient module

Line2: Inject the HttpClient by using the constructor.

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

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

Line5: Create the POST request with returning the response.

 04. Send the file using http POST request

Subscribe to the htpp POST request in fileUpload() method in the file-upload.component.ts

Notice: Post method in HttlClient, return an Observable. So, subscribing this Observable will send the POST request to specified url because observable are executed until subscribing on it.   Now, the code in 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
}
}

Line 6: Import the file service into our file-upload.component.ts.

Line 7: Inject the file service using the constructor

Line 8: Subscribe the observable.

Line 9: Reset the file upload element.

Now, let me show you the functionality until now.

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

Now you completed the first part of file upload tutorial.

If you have any problem, please comment in the comment section. If you like this post don’t forget to share. Please like to our Facebook page to get latest programming and technology tricks.

Find the project on the Github from here.

Thank you for reading.

Please follow us:
error
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

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE