banner



How To Upload Images To A Server From Angular 5

Angular 9 and Ionic 5 Chat App

In this tutorial function, we'll acquire to customize/upload user contour photos. We assume no previous knowledge of TypeScript which is the programming language used in both Ionic/Angular and Node/Nest.js used to build both the front-stop and dorsum-finish of our chat awarding. Nosotros'll be also explaining bones concepts such as imports, decorators, Async/Await and HTML5 FormData.

These are all the tutorial parts:

  • Building a Conversation App with TypeScript/Node.js, Ionic five/Athwart 9 & PubNub/Chatkit
  • Add JWT Remainder API Authentication to Your Node.js/TypeScript Backend with TypeORM and SQLite3 Database
  • Building Chat App Frontend UI with JWT Auth Using Ionic v/Athwart 9
  • Adding UI Guards, Car-Scrolling, Auth State, Typing Indicators and File Attachments with FileReader to your Angular 9/Ionic five Chat App
  • Chat Read Cursors with Athwart 9/Ionic v Chat App: Working with Textarea Keydown/Focusin Events
  • Athwart ix/Ionic five Chat App: Unsubscribe from RxJS Subjects, OnDestroy/OnInit and ChangeDetectorRef
  • Upload Images In TypeScript/Node & Angular 9/Ionic 5: Working with Imports, Decorators, Async/Wait and FormData
  • Private Chat Rooms in Angular 9/Ionic 5: Working with TypeScript Strings, Arrays, Promises, and RxJS Behavior/Replay Subjects

If you lot are a TypeScript beginner, you lot'll also acquire throughout this tutorial how to use bones concepts of the language such every bit:

  • How to define TypeScript class methods,
  • How to define TypeScript course variables.
  • How to utilize TypeScript decorators, which are heavily used past both Angular and Nest.js,
  • How to import APIs from TypeScript modules,
  • How to employ the async/look syntax in TypeScript,
  • How to utilize HTML FormData in TypeScript, etc.

Yous'll learn nigh new concepts in Node/Nest.js, Athwart and Ionic.

Before getting started, let's see a summary of what we are going to learn throughout this tutorial. We'll learn about:

  • How to upload contour photos or images with Node, Nest.js, TypeScript, Angular nine and Ionic 5,
  • How to implement image files uploading in our Node/Nest.js backend with Multer, Multer is a middleware that supports the multipart/form-information encoding blazon simply, that'due south mainly used for uploading files in the web.
  • How to upload a single file past using the FileInterceptor() and @UploadedFile() TypeScript decorators, then access the file from the file holding in the request object in Node/Nest.js.
  • How to apply the sendFile() method (which is supported in Express v4.viii.0+) provided by the injected response object that transfers a file at the given path (passed every bit the first statement) and sets the Content-Type response HTTP header field based on the filename's extension.
  • How to import and use the Get, Res and Param custom TypeScript decorators from the @nestjs/common package. Decorating a TypeScript method with the @Get() decorator allows Node/Nest.js to create a REST API endpoint for a particular route path and map every corresponding HTTP request to the method. The @Param decorator allows you to access the value of a route parameter passed through the URL. The @Res() decorator allows you to inject a library-specific response object. You can observe more than details nigh information technology from the Express docs.
  • How to create a Remainder API route to enable our Node/Nest.js application to serve static files from an uploads folder.
  • How to create a chat profile page in the Angular/Ionic 5 frontend.
  • How to use use the async keyword with the Angular ngOnInit() life-cycle method to be able to employ the wait keyword in the trunk of the method.
  • How to create an Athwart form and bind the ngSubmit event to our uploadAvatar() method that will be chosen when the users click on the submit button. The uploadAvatar() method takes a reference to the form created using a template reference variable (#f="ngForm").
  • How to bind an attachFile() TypeScript method to the modify event of the HTML file input tag which will be called when the user clicks the Cull File push button to select a file.
  • How to build an Ionic 5/Angular 9 chat profile UI.
  • How to import and inject Angular 9 HttpClient and Ionic v Storage services for sending HTTP requests and accessing the device or spider web browser storage.
  • How to retrieve the currently logged-in user ID from localStorage with Ionic five Storage.
  • How to add together the TypeScript method that actually uploads the selected file to the Node.js server forth with the currently logged in user using an Athwart HttpClient mail request and HTML5 FormData.
  • How to add an Ionic v button that will allow users to navigate to the contour page via the Angular routerLink directive.

This tutorial is based on the Angular ix and Ionic 5 awarding we've built in the previous series. You can get the source lawmaking of this role from this GitHub repository.

Note: Chatkit is the hosted chat service provided by Pusher which is now retired. You tin can either use your ain hosted chat server with an open source solution like https://chatsdk.co/ which is based on Firebase or employ PubNub Chat, an alternative service for Chatkit.

In the previous tutorials, we've started edifice a mobile awarding with Ionic 5 and Angular 9 on the frontend and Node Nest.js on the backend. For chat features, nosotros've used Pusher Chatkit which provides out of the box chat features commonly used in nigh popular chat apps. Nosotros've added features like typing indicators and file attachments. At present, nosotros'll continue with our demo awarding by implementing other functionalities such as read cursors and profile photos.

Note: Yous tin can read the previous tutorials where we've built our demo conversation application from these links:

Building a Chat App with Node.js, TypeScript, Ionic five, and Angular ix: The Auth Backend Building a Conversation App with Node.js, TypeScript, Ionic 5, and Angular 9: The Frontend Calculation Profile Photos and Read Cursors to your Ionic 5/Athwart 9 Conversation App Adding Hallmark, Typing indicators and File Attachments to your Ionic 5/Angular 9 Chat App

TypeScript provides various ways for imports. When the module exports an object with properties, you lot can apply the import * equally mymodule from "mymodule"; syntax or or pick the names you want to import using import { symbol } from "mofule";

Both Angular and Nest.js are based on TypeScript so you lot'll be using the aforementioned import syntax for importing the built-in APIs of the frameworks before yous tin call them in your code.

Uploading Profile Photos with Node, TypeScript, Angular 9 and Ionic 5

Most conversation applications provide a way for users to add a profile photo. Chatkit allows y'all to assign profile photos to users but doesn't provide storage and so you lot need to upload images to your own Node/Nest.js server.

Implementing Image Files Uploading in the Node Nest.js Backend with Multer

Node Nest.js uses the multer middleware for supporting file uploading. The middleware can be configured and adjusted depending on your requirements.

Note: Multer is a middleware that works but with the multipart/form-data encoding blazon, which is primarily used for uploading files.

You tin can upload a single file by using the FileInterceptor() and @UploadedFile() decorators, and you can then access the file from the file property in the request object. Let's see this by example.

Open the src/auth/auth.service.ts file and add the following method:

                          // src/auth/auth.service.ts     public async updateUserAvatar(userData: any): Promise<any>{       const userId = userData.userId;       const avatarURL = userData.avatarURL;       return this.chatkit.updateUser({id:userId, avatarURL:avatarURL});     }                      

This TypeScript method will exist used to update the user avatar. Information technology merely calls the updateUser() method available in the chatkit instance which takes an object that provides the ID of the user and the avatar URL.

Serving Static Files from our Node/Nest.js Backend

Next, open the src/app.controller.ts file and add the imports for the Become, Res and Param TypeScript decorators from the @nestjs/common bundle:

            // src/app.controller.ts  import { Get, Mail, Body,Request, Res, Param, Controller} from '@nestjs/mutual';                      

Note: the other symbols are already imported from the previous tutorials.

Next, add together the post-obit imports which are necessary for file uploading:

            // src/app.controller.ts  import { UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common';                      

Adjacent, import diskStorage from the multer packet and extname from the path module:

            // src/app.controller.ts  import { diskStorage } from 'multer'; import { extname } from 'path';                      

Next, add together the following road:

                          // src/app.controller.ts    @Go('uploads/:imgId')   async uploads(@Param('imgId') imgId, @Res() res): Promise<any> {     res.sendFile(imgId, { root: 'uploads'});   }                      

The @Go() decorator before the uploads() method tells Node/Nest.js to create an endpoint for this particular route path and map every corresponding request to this handler.

The @Param decorator allows united states of america to get the value of the imgId parameter passed through the URL.

The @Res() decorator allows us to inject a library-specific response object. You can detect more than details about it from the Express docs.

The injected response object provides the sendFile() method (which is supported in Limited v4.8.0+) that transfers a file at the given path (passed as the first argument) and sets the Content-Type response HTTP header field based on the filename's extension.

Since we specified the root option in the options object (passed every bit the second argument), the path argument tin be a relative path to the file (In our case it'south only the name of the file). In our instance, the file will be transferred from the uploads binder.

This route will permit our Node/Nest.js application to serve static files from an uploads binder.

Now, let's test if our application is serving files correctly. In the root binder of your Node server, create an uploads folder:

Note: If y'all don't manually create this folder it will automatically be created past Node/Nest.js merely in our case we need to add together our user default avatar to this binder that's why we are manually creating it.

Setting the Default Contour Image File

Next, add together the default user avatar that nosotros used before from the https://image.flaticon.com/icons/png/128/149/149071.png link in the uploads folder (relieve it as avatar.png).

Next, open the src/app/auth/auth.service.ts file, locate the createUser() method and modify the default value of the avatarURL variable to indicate to our avatar.png image in our server:

            // src/app/auth/auth.service.ts  const avatarURL = "http://127.0.0.1:3000/uploads/avatar.png";                      

At present, we are serving the default avatar from our server.

At this indicate, if you examination both your frontend and backend apps, yous should be able to see the default avatar assigned to new users in your awarding:

Calculation a Node/Nest.js Road for Uploading Image Files

Now that we are able to serve static image files from our backend application, let's add together the road for assuasive users to update their profile photos.

Open the src/app.controller.ts file and add the following route:

                          // src/app.controller.ts    @Post('avatar')   @UseInterceptors(FileInterceptor('file',     {       storage: diskStorage({         destination: './uploads',         filename: (req, file, cb) => {           const randomName = Array(32).fill up(cypher).map(() => (Math.round(Math.random() * xvi)).toString(sixteen)).join('')           return cb(zippo, `${randomName}${extname(file.originalname)}`)         }       })     }   )   )   uploadAvatar(@Torso() userData, @UploadedFile() file) {     allow userId = userData.userId;     this.authService.updateUserAvatar({       userId: userId,       avatarURL: `${this.SERVER_URL}${file.path}`     });     return {       avatarURL:  `${this.SERVER_URL}${file.path}`     };   }                      

This allows yous to send a Postal service asking to the 127.0.0.one:3000/avatar endpoint from the frontend application to update the profile photograph.

The TypeScript uploadAvatar() method is mapped to the /avatar API endpoint and accepts Post requests which comprise the user identifier and the uploaded file. In the body of the method, we merely telephone call the TypeScript updateUserAvatar() method defined in AuthService to update the user avatar with the URL of the uploaded image.

Also in your controller add the TypeScript SERVER_URL variable which holds the address of your server:

            // src/app.controller.ts  SERVER_URL = 'http://localhost:3000/';                      

Adding the Profile Page in the Athwart 9/Ionic v Frontend

Afterward implementing file uploading in the backend, let'due south now add a profile folio in our Angular 9/Ionic 5 application which allows users to upload their contour image avatars to the server.

Open a new concluding and navigate to your frontend folder using:

            $ cd chatkit-ionic-demo/frontend                      

Next, generate a new Ionic page using the post-obit command:

            $ ionic generate page profile                      

This will create a src/app/profile folder with the necessary files and add a profile route to the src/app/app-routing.module.ts file:

                          // src/app/app-routing.module.ts     { path: 'profile', loadChildren: './profile/profile.module#ProfilePageModule' },                      

Next, open up the src/app/home/dwelling.page.html file and add a button that will take us to the profile page only beneath the Commencement CHATTING button:

                          <!-- src/app/domicile/abode.folio.html -->      <ion-button color="light" outline size="big" [routerLink]="'/profile'">       <ion-icon proper noun="settings"></ion-icon>       Profile settings     </ion-button>                      

This is a screenshot of the UI:

Building an Ionic five Conversation Contour UI with Angular Forms

Adjacent, open the src/app/profile/contour.page.html file and update its content with the following code:

            <!-- src/app/profile/profile.page.html -->  <ion-header>   <ion-toolbar color="primary">     <ion-title>       Chatkit Demo     </ion-championship>    </ion-toolbar> </ion-header> <ion-content padding>   <form #f="ngForm" (ngSubmit)="uploadAvatar(f)">     <ion-grid>       <ion-row justify-content-centre>         <ion-col marshal-self-center size-doctor="6" size-lg="five" size-xs="12">           <div text-center>             <h3>Update your contour photo</h3>           </div>           <div padding>             <ion-item>                 <img *ngIf="avatarURL" [src]="avatarURL"                 />             </ion-item>             <ion-item>               <input name="file" blazon="file" have="image/x-png,image/jpeg" (change)="attachFile($event)" ngModel required />             </ion-item>           </div>           <div padding>             <ion-button size="large" blazon="submit" [disabled]="f.invalid" expand="block">Update photo</ion-button>           </div>         </ion-col>       </ion-row>     </ion-grid>   </course> </ion-content>                      

We create an Angular form and nosotros bind the ngSubmit result to an uploadAvatar() method that will be called when the users click on the submit button. The uploadAvatar() TypeScript method takes a reference to the class created using an Angular template reference variable (#f="ngForm").

We also bind an attachFile() TypeScript method to the change consequence of the file input tag which will be called when the user clicks the Choose File push button and select a file.

Importing and Injecting Angular nine HttpClient and Ionic five Storage

Side by side, we demand to define the uploadAvatar() and attachFile() TypeScript methods. Open the src/app/profile/profile.page.ts file and kickoff by adding the following imports:

            // src/app/profile/profile.page.ts  import { HttpClient } from '@angular/common/http'; import { Storage } from '@ionic/storage';                      

We import HttpClient for sending POST requests to the server and the Ionic Storage service for working with local storage.

Next, define SERVER_URL, fileToUpload, userId and avatarURL TypeScript variables:

            // src/app/contour/profile.page.ts  @Component({   selector: 'app-profile',   templateUrl: './profile.page.html',   styleUrls: ['./profile.page.scss'], }) consign class ProfilePage implements OnInit {   SERVER_URL = 'http://localhost:3000/avatar';   fileToUpload: File = null;   userId = nada;   avatarURL;                      

The SERVER_URL variable simply holds the server endpoint for uploading user profiles.

The fileToUpload variable volition concord the selected image file that will be uploaded to the server.

Next, inject the HttpClient and Storage services via the constructor:

            // src/app/profile/profile.page.ts    constructor(individual httpClient: HttpClient, private storage: Storage) { }                      

Retrieving the Currently Logged-In User ID from localStorage with Ionic five Storage

Next, we demand to retrieve the ID of the currently logged in user from localStorage in the ngOnInit() life-bike method of the page:

                          // src/app/contour/profile.folio.ts    async ngOnInit() {     this.userId =  await this.storage.get("USER_ID");   }                      

We simply phone call the get() method of the Storage service to remember the USER_ID and assign it to the userId variable nosotros defined before.

Note: Make certain to add the async keyword before the ngOnInit() method to be able to use the look keyword in the body of the method.

Next, we define the attachFile() method:

                          // src/app/profile/contour.page.ts    attachFile(e){     if (e.target.files.length == 0) {       console.log("No file selected!");       return     }     let file: File = e.target.files[0];     this.fileToUpload = file;   }                      

This method volition be called when the user selects a file. If a file is selected information technology will exist stored in the fileToUpload variable we divers earlier.

Uploading Epitome Files with Athwart nine HttpClient and FormData

At present that we have added the code to retrieve the user identifier from the local storage and select the file from the user drive, let's add the method that uploads the file to the Node server from Athwart with FormData along with the currently logged in user using Athwart 9 HttpClient and HTML5 FormData:

                          // src/app/profile/profile.page.ts    uploadAvatar(f){     let formData = new FormData();      formData.suspend('file', this.fileToUpload, this.fileToUpload.name);      formData.append('userId', this.userId);     this.httpClient.mail service(this.SERVER_URL, formData).subscribe((res) => {      console.log(res);     this.avatarURL = res['avatarURL'];     });     render imitation;        }                      

Nosotros use the FormData interface to create a form object and we use the suspend() method to add fields to the course (the file field which contains the file to upload and the userId field which contains the user identifier). Finally we send the form information with a Postal service request using the post() method of HttpClient.

What'southward FormData?

Here is the definition of FormData from Mozilla docs:

The FormData interface provides a way to easily construct a gear up of cardinal/value pairs representing form fields and their values, which tin then exist easily sent using the XMLHttpRequest.transport() method. It uses the same format a grade would apply if the encoding type were set to "multipart/form-data".

That's it we are finished with this role dealing with updating the user avatar. This is a screenshot of the profile page afterwards nosotros uploaded a new avatar for the currently logged in user:

Conclusion

In this tutorial, we've seen how to upload and serve user avatars in our Ionic five, Athwart 9 and Node/Nest.js chat application and we likewise implemented chat read cursors that show users the position of the latest message they have read and the count of their unread letters in the room. Y'all tin get the source code from this GitHub repository.


Source: https://www.techiediaries.com/angular/upload-images-typescript-node-ionic-imports-decorators-async-await-formdata/

Posted by: tuckersibareaught.blogspot.com

0 Response to "How To Upload Images To A Server From Angular 5"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel