How to Upload Images to a Server From Angular 5

Athwart v Image Uploader Component — API Integration

Hi everyone, my proper name is Dan, I'm young Web Developer who passionated by JavaScript. Now I am developer on frontend side and make magic things in Angular 5. This article is addressed to newbies, this is my first tutorial virtually programming especially — How to create an image uploader which you volition be able to use in your any further project. Okay let's go.

Create new component

Usually this component must be placed in shared module, considering you lot should admission it globally.

          ng thousand c prototype-uploader        

Create simple epitome uploader

After we create a component open up image-uploader.component.html and create a simple input.

          <input type="file" id="uploader"/>        

In my example, uploader is a elementary icon which is centered in parent cake. I use FontAwesome (you tin can replace this with any image or text) icon and any uncomplicated styles.

          <label class="uploader-circle">
<i grade="fas fa-plus"></i>
<input type="file" id="uploader"/>
</label>

OPTIONAL: If you want to use FontAwesome icon import this library in index.html

          <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" integrity="sha384-3AB7yXWz4OeoZcPbieVW64vVXEwADiYyAEhwilzWsLw+9FgqpyjjStpPnpBO8o8S"
crossorigin="bearding">

Open image-uploader.component.scss and add the following styles:

          input {
display: none;
}

characterization.uploader-circumvolve {
$size: 23px;
cursor: pointer;
width: $size;
height: $size;
line-pinnacle: 19px;
text-marshal: eye;
edge-radius: 100%;
// Using position attribute
position: absolute; // Give accented position
tiptop: 50%; // Vertical center
left: 50%; // Horizontal center
transform: translate(-fifty%, -50%); // The icon is centered past the style regardless of the size of the parent
transition: all .2s ease-out;

i {
font-size: 24px;
color: #000;
}
}

Now, our prototype uploader looks similar this:

Image uploader

Functionality cosmos & API connection

First of all, nosotros use HttpClient for request, for this we import HttpClientModule. For afterward use of the component, we export it.

                      import            {NgModule}            from            '@angular/core';
import {CommonModule} from '@athwart/common';
import {HttpClientModule} from '@angular/mutual/http'; // Import Path

@NgModule({
imports: [
CommonModule,
HttpClientModule // Import HttpClientModule
],
declarations: [
ImageUploaderComponent
],
exports: [
ImageUploaderComponent // Consign Image Uplaoder
],
providers: []
})
export class SharedModule {
}

Second , open image-uploader.component.ts and import in constructor HttpClient.

                      import            {Component}            from            '@angular/core';
import {HttpClient} from '@athwart/common/http';

@Component({
selector: 'app-prototype-uploader',
templateUrl: './epitome-uploader.component.html',
styleUrls: ['./epitome-uploader.component.scss']
})
export course ImageUploaderComponent {

constructor(individual http: HttpClient) {
}

}

Create method which receive uploader params:

                      import            {Component}            from            '@angular/core';
import {HttpClient} from '@angular/mutual/http';

@Component({
selector: 'app-epitome-uploader',
templateUrl: './paradigm-uploader.component.html',
styleUrls: ['./image-uploader.component.scss']
})
export grade ImageUploaderComponent {

selectedFile: File = cypher;

constructor(private http: HttpClient) {
}

/**
* Validate uploader params
*
@param event
*/
public onFileSelected(effect) {
this.selectedFile = <File>event.target.files[0];
if (this.selectedFile) {
// If selected file exist make upload asking
}
}

}

Call this method when uploader params changed and send $event.

          <label class="uploader-circle">
<i class="fas fa-plus"></i>
<input type="file" (alter)="onFileSelected($event)" id="uploader"/>
</label>

OPTIONAL: If we want that uploader let'southward upload only image, we use input attribute take.

          <input blazon="file" (change)="onFileSelected($event)" have="image/*" id="uploader"/>        

Send request to server for uploading epitome.

                      import            {Component}            from            '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
selector: 'app-image-uploader',
templateUrl: './image-uploader.component.html',
styleUrls: ['./image-uploader.component.scss']
})
consign course ImageUploaderComponent {

selectedFile: File = null;
public image: any;

constructor(private http: HttpClient) {
}

/**
* Validate uploader params
*
@param event
*/
public onFileSelected(outcome) {
this.selectedFile = <File>event.target.files[0];
if (this.selectedFile) {
return this.upload();
}
}

/**
* Upload image to server and receive image object
*/
upload() {
const fd = new FormData();
fd.suspend('image', this.selectedFile, this.selectedFile.name);
this.http.post('http://instance.com/upload/image', fd).subscribe((res: any) => {
this.image = res.data;
}, (err: whatsoever) => {
// Prove error message or make something.
});
}

}

In our case if it'southward alright our request returns u.s. following response:

Request Answer

The last thing which we need to do, is to return the response to our class. Let's do it through Athwart Output. It ways that at every time when we upload prototype we receive response from the server to grade.

                      import            {Component, EventEmitter, Output}            from            '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
selector: 'app-image-uploader',
templateUrl: './epitome-uploader.component.html',
styleUrls: ['./image-uploader.component.scss']
})
export form ImageUploaderComponent {

selectedFile: File = null;
@Output() outcome = new EventEmitter();
public image: any;

constructor(private http: HttpClient) {
}

/**
* Validate uploader params
*
@param event
*/
public onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
if (this.selectedFile) {
return this.upload();
}
}

/**
* Upload prototype to server and receive image object
*/
upload() {
const fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.proper noun);
this.http.postal service('http://example.com/upload/image', fd).subscribe((res: whatever) => {
this.paradigm = res.data;
this.result.emit(this.epitome);
}, (err: whatsoever) => {
// Show mistake message or make something.
});
}

}

How we employ image uploader

When we have a form with paradigm uploader nosotros simply apply it.

          <class>
<input blazon="text" placeholder="Name" />
<div grade="uploader">
<app-epitome-uploader (event)="giveImage($event)"></app-prototype-uploader> </div>
</class>

Nota bene: Paradigm uploader's parent should have position: relative;

In giveImage method nosotros take response from image-uploader..

          public giveImage(issue)
{
console.log(event);
}

Event console log

Terminal Result

Conclusion

If we create uploader like carve up component we can employ them in every form which nosotros use. It's like shooting fish in a barrel to maintain and add new features.

Thank you for attending, waiting for your feedback.

thomasforeadfat67.blogspot.com

Source: https://medium.com/@dancornilov/angular-5-image-uploader-component-api-integration-69dadf3e2728

Belum ada Komentar untuk "How to Upload Images to a Server From Angular 5"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel