Ionic 4 Profile Image Upload to Serve
INTRODUCTION
In this tutorial, we will build elementary image uploader in Ionic 4 Framework and we will likewise preview the uplaoded image in our app. I hope that you lot already know the basics of Ionic. We volition utilize CLI, HTML CSS, TS etc.
What Is Ionic?
Ionic is a popular framework for creating hybrid mobile applications using the wildly pop Angular framework.
Do you desire to create hybrid apps that work on both Android and iOS? With Ionic, you no longer need to create carve up apps for Android and iOS operating systems. Instead, with Ionic, you tin can create one code base that is compatible with both Android and iOS.
Ane great benefit of using Ionic is that yous don't need to larn a new language from scratch. Developers can create full-featured mobile apps for Android and iOS using technologies they are already familiar with, like JavaScript, HTML, and CSS.
PREREQUISITES
First of all we volition start with installing Node and Ionic if you lot don't have already installed. Follow Setting upward Ionic 4 Tutorial or visit Ionic Framework docs for more than info.
For a trivial quick view, you lot can utilise below command to create blank new Ionic Project:
ionic first <name> blank --type=angular --spec false
Now we've got everything we need set up, and so allow's get started.
Ionic iv Steps
Step 1 — Creating an Ionic 4 app.
Step ii — Using ImgBB website for uploading images.
Step 3 — Using HttpClientModule for sending http requests.
Step 4 — Upload Images via API and Preview them.
Stride v —Run the app on browser, android or ios to test app.
Before we go on further, let me show you, what exactly we are going to build:
Promise you guys like it. Let's move on to the actual functionality of the code.
** — Permit'south Start
Now go to src/app/app.module.ts and import HttpClientModule like the following code:
import { NgModule } from '@angular/cadre';
import { BrowserModule } from '@athwart/platform-browser';
import { RouteReuseStrategy } from '@angular/router';import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,
HttpClientModule
],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Once this is done, before we continue further nosotros need imgBB website API key, for that we have to create account there first. So go head and create your account there and then let's see how we can get API from there.
So, once y'all are done with creating business relationship in imgBB. In your dashboard, click on top right about menu, and then click on API button. Like below:
after that, click on AddKey push button on the summit of the folio and get your apiKey from there. Like below:
That's it. Now let'due south move on to our Ionic code and come across how we can upload images from our app and preview them.
Go to habitation.page.html and implement this code:
<ion-content [fullscreen] ="true">
<ion-list lines ="full">
<img [src] ="imageURL ? imageURL : 'assets/dummy-profile-pic.png'" grade ="rounded mx-auto d-block img-thumbnail" alt ="HA" (click) ="uploadFile()">
<input id ="fileBtn" type ="file" fashion =" display: none" (change) ="fileChanged($issue)" have ="paradigm/*" grade ="filebtn" #fileButton />
<br /><br />
</ion-listing>
</ion-content>
Now go to habitation.page.ts and implement this code:
import {Component, ViewChild} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {AlertController, LoadingController} from '@ionic/athwart';
bookingForm : FormGroup;imageURL: any = nothing;
@ViewChild('fileButton', {static: imitation}) fileButton;
imgBBKey = '<YourApiKeyHere>'; // example: imgBBKey = 'abc...'constructor(
individual router: Router,
private httpClient: HttpClient,
private alertCtrl: AlertController,
private loadCtrL: LoadingController,
) {}
async presentAlert(title: string, content: string) {
const alarm = await this.alertCtrl.create({
header: title,
bulletin: content,
buttons: ['OK']
});
wait alert.nowadays();
}uploadFile() {
const btn = document.getElementById('fileBtn');
btn.click();
}fileChanged(consequence) {
const files = event.target.files;
console.log(files);
const imgData = event.target.files[0];
const reader = new FileReader();
reader.onload = () => {
// this.imageURL = reader.result;
const class = new FormData();
form.suspend('image', imgData);
this.loadCtrL.create({
message: 'Delight Wait...',
spinner: 'lines'
}).and so(elementEl => {
elementEl.present();
this.httpClient.postal service('https://api.imgbb.com/1/upload?key=' + this.imgBBKey, course).subscribe(res => {
elementEl.dismiss();
console.log(res);
if (res['status'] === 200) {
this.imageURL = res['data'].display_url;
}
}, (err) => {
elementEl.dismiss();
if (err) {
this.presentAlert('err: ' + err['error'].fault.code, err['fault'].error.message);
}
});
});
};
reader.readAsDataURL(upshot.target.files[0]);
}
That'due south what we have to practise. Don't forget to replace the apiKey with your imgBBApiKey . Now what this all code will do???. When nosotros will tap on the image in our app, it will ask us to select whatsoever image that we would like to preview, when will select any image, it will upload that paradigm to our imgBB account and imgBB will return us imgURL which nosotros tin store to brandish our image in our app. And that'due south what we are doing in our code here. Nosotros likewise created a presentAlert (title: string , content: string ) {} part which volition present an alarm with mistake message if for somehow image not uploaded, etc.
Perfect, Nosotros are done with information technology. Then we can run the app now. We tin can run this app on device or emulator. The easiest way to run our app on phone using Ionic Serve. Run the post-obit command in terminal and w8 for this to launch in browser.
ionic serve Your app will appear automatically in Chrome or any browser you've installed, after terminal finished compiling app.
We successfully uploaded an image and preview in our Ionic App. So, we can check it browser, also in android or iPhone and even on real device. Do you wanna build information technology???, To build our app, run this command:
$ ionic cordova build android --aot --prod This will build your app and later on building, you can test your Ionic App in a real device.
Conclusion
If you take any question, let me know in the comments below and I will attempt to best to help you!
Source: https://ionictemplates.blogspot.com/2020/11/ionic-45-select-image-upload-and-display.html
Belum ada Komentar untuk "Ionic 4 Profile Image Upload to Serve"
Posting Komentar