How to Set Profile Picture Using Angular 7 and JSON Server REST API

https://i.sstatic.net/VQcAd.png

After successfully creating a CRUD app with Angular using Json server and the HttpClient module, I saved contact objects in a JSON file named db.json.

{"contact": [
{
  "name": "",
  "email": "",
  "phone": "",
  "image": "",
  "id": 1
},
{
  "name": "",
  "email": "",
  "phone": "",
  "image": "",
  "id": 2}]}

However, I am facing an issue on how to upload an image file from an input tag in Angular. The ContactCreateComponent allows me to create a contact object by importing data from restApiService.

import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { RestApiService } from "../shared/rest-api.service";

@Component({
  selector: 'app-contact-create',
  templateUrl: './contact-create.component.html',
  styleUrls: ['./contact-create.component.css']
})
export class ContactCreateComponent implements OnInit {
  @Input() contactDetails = { name: '', email: '', phone:"",image:"" }
 
  constructor( public restApi: RestApiService, 
    public router: Router,) {
    }

  ngOnInit() {
  }
  addContact(dataContact) {
    this.restApi.createContact(this.contactDetails).subscribe((data: {}) => {
      this.router.navigate(['/contact-list'])
    })
  }
}

Here is the source code for my restApiService:

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { Contact } from '../shared/contact';
import { Observable,throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class RestApiService {
  apiURL ="http://localhost:3000"
  constructor(private http:HttpClient) { }

  
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }  

  getContacts(): Observable<Contact> {
    return this.http.get<Contact>(this.apiURL + '/contact')
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }
  getContact(id): Observable<Contact> {
    return this.http.get<Contact>(this.apiURL + '/contact/' + id)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  

  createContact(Contact): Observable<Contact> {
    return this.http.post<Contact>(this.apiURL + '/contact', JSON.stringify(Contact), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }  
  updateContact(id, Contact): Observable<Contact> {
    return this.http.put<Contact>(this.apiURL + '/contact/' + id, JSON.stringify(Contact), this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }
  deleteContact(id){
    return this.http.delete<Contact>(this.apiURL + '/contact/' + id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }


  handleError(error) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    window.alert(errorMessage);
    return throwError(errorMessage);
 }
}

Thank you for your assistance.

Answer №1

If you want to upload an image, FormData is the way to go.

Here is a service method example:

public sendImage(image: File): Observable<Response> {
   const formData = new FormData();

   formData.append('image', image);

   return this.http.post('/api/v1/image-upload', formData);
 }

To use this method, pass in the file object obtained from the input field.

For example:

var file = document.getElementById('myFile').files[0];

Alternatively, you can handle the file selection change event like this:

fileSelected(event: any): void {
  let file =  event.target.files[0];

 }

Answer №2

To properly bind selected files to a form field, you will need to develop a custom directive.

Review the following code snippet and integrate the directive into your application: https://gist.github.com/sheikalthaf/85c19d41bccf218d6bc962daa75a7943

Once implemented, add the ngu-file-ref attribute to your input[type="file"] element. Subsequently, inspect the form value to verify that the file formats are correctly displayed in the field.

Prior to sending the data to an API, remember to convert it to FormData by referring to the documentation available at: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mapping values of 2 objects in TypeScript through an interface

I am currently working with two objects, objA and objB. There is a function that I have, which takes a value from objB and a key from objA as arguments. const objA = { a:"a", b:"b" } const objB = { a:"a", b:"b&qu ...

Creating a build task in Visual Studio Code with universal TypeScript compiler settings

Our project has the following structure: +-- views +-- viewXXX +-- ts ¦ +-- controller.ts ¦ +-- helper.ts ¦ +-- ... (*.ts) +-- viewXXX.ctrl.js // this is the desired output file +-- viewXXX.c ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Guide on customizing VS Code's Explorer to display angular js icons

How can you customize the icons displayed in Explorer within VS Code by adding a specific addon procedure? https://i.sstatic.net/KSMwC.png https://i.sstatic.net/2mFMq.png ...

The Python json.loads function throws a ValueError when there is extra data present

I am extracting specific data from a JSON file named "new.json" and filtering it to save in a new JSON file. Here is the code snippet I am using: import json with open('new.json') as infile: data = json.load(infile) for item in data: iden ...

Administer styles to individual Angular Material components using external CSS files

I am attempting to customize a specific mat input element in my application using an external CSS file. For instance, I have imported textfield.css and style.css files for this purpose. Let me provide some code snippets below: <mat-form-field> ...

Retrieving JSON-formatted data from the database

I am working on a simple PHP script that fetches data from a database and formats it into JSON. Here is an example of how the output looks: [ { S.no: "1", News: "http://example.com/news/1.pdf", Date: "2022-01-01", news_desc: "Example News Article 1" ...

When using Angular9 with PrimeNG fullcalendar, it may encounter issues such as errors stating "Cannot find namespace 'FullCalendarVDom'." and "Please import the top-level fullcalendar lib"

Using primeng p-fullcalendar in my angular application. Encountering an error in the command-line: 'Cannot find namespace 'FullCalendarVDom' Also seeing this error in the browser: 'Please import the top-level fullcalendar lib before a ...

Ways to retrieve multiple values from the backend using observables

I am offering a service that connects to the backend. After making a request, I expect to receive two values, x1 and x2. How can I modify my code to handle this? Code: public startWebService(fieldGeometry) { var endpointURL = this.buildEndpointURLForLIDA ...

Avoid changing the button color to a lighter shade when it is clicked

Is there a way to prevent button text from changing to a lighter color after clicking? I am facing an issue where the button I set to red turns slightly whiteish after it is clicked. How can I ensure that the button stays red at all times? Header Toolbar ...

Parsing JSON results from Alamofire using SwiftyJSON

I am struggling to populate a table view using SwiftyJSON as it does not seem to parse the JSON results from Alamofire. let getRouteURL = "http://example.com/api/Trafi/GetRoute/" Alamofire.request(getRouteURL, method: HTTPMethod.post, parameters: para ...

Looping through various sizes of JSON files using a for loop

If I have multiple JSON files with different structures like the following examples: { "a": "1", "b": "2", "c": "3", "d": "4" } Example 2: { "a": ...

I am using an A-frame animation-mixer. What is the best way to seamlessly switch between different json model animation clips

Recently, I started using A-Frame and have a question regarding the animation-mixer. For my webVR project, I am animating a rigged json model. Currently, I have successfully loaded and animated the model in the idle state: <a-entity id ...

Accessing attributes with numeric identifiers

Currently, I am using node.js and faced with the task of parsing the object below: { state: { desired: { '1': '0', '151': '2', hdr: [Object] }, reported: { '1': '0', '151&apos ...

The sorting function and URL update seem to be caught in an endless loop, unable to break

I am attempting to update the URL when triggering sorting on a material table's column, like so: http://localhost:4200/cars?find=m&sort=make:desc If a URL includes a sort parameter, the table should be sorted accordingly. Currently, clicking on ...

Unable to save information in the database using Json in asp.net

I'm having trouble saving my data in a database using JSON. The code I'm currently using doesn't display any errors, but it also doesn't save the data. Can someone please help me out? I am new to working with JSON. function myfun() { ...

Managing various names of child objects in a recursive manner

I'm currently facing a challenge while working on a nested JSON feed using D3.js Although my code is functioning properly when the child object is named children, I am interested in displaying nodes for other objects as well, not just the ones labele ...

Unsubscribing EventListener during ngOnDestroy

Here is my implementation of a directive in Angular. I am facing an issue with removing the event listener in this case: import { Directive, ElementRef, OnDestroy } from "@angular/core"; @Directive({ selector: "[Enter]" }) export class Enter implemen ...