Adding Images Using Angular 8

I'm encountering difficulties with image upload in the file located at '../src/app/assets/'. Below is the Form I am using:

 <form [formGroup]="formRegister" novalidate="">  
    <div class="form-group">
        <label for="exampleInputImage">Image</label>
        <input type="file" (change)="onFileSelect($event)" name="image" 
           class="form-control" placeholder="Enter your image">
    </div>
</form>
<button type="button" (click)="onRegister()">Submit</button>

In my TypeScript file (ts)

formRegister: FormGroup;
errorMail: string = "";
selectedFile: File = null;

constructor(private appService: AppServiceService, private http: HttpClient) { }

ngOnInit() {
this.formRegister = new FormGroup({      
  image: new FormControl('', [Validators.required])
});
}


onFileSelect(event) {
  console.log("event : ", event);
  this.selectedFile = <File>event.target.files[0];
 }

onRegister(): void {
const fd = new FormData();
fd.append('image', this.selectedFile);
const req = new HttpRequest('POST', '../src/app/assets/', fd);
this.http.request(req).subscribe(events => {
  console.log("Upload Image", events);
},
  (err: HttpErrorResponse) => {
    console.log("Error: ", err.message);    // Show error, if any.
  });
}

In my console, I'm seeing the following errors: http://localhost:4200/src/app/assets/ 404 (Not Found)

Please help me identify where the issue lies in my code. Thank you.

Answer №1

Applying an image directly in a folder using Angular alone is not feasible. One workaround is to convert the image into base64 format and store it as a string.

If you wish to save images in a specific folder, you will need to utilize a server such as Node Js or Spring Boot.

Thank you for your attention.

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

Exploring nested contexts in react testing library with renderHook

This is a sample code snippet in TypeScript that uses React and Testing Library: import React, { FC, useEffect, useMemo, useState } from 'react'; import { renderHook, waitFor } from '@testing-library/react'; interface PropsCtx { inpu ...

Tips for navigating through a nested JSON object with loops

Is it possible to access the value of the Address object within an interface in Angular using *ngFor? export interface User { id: number; name: string; username: string; email: string; address: Address; } export interface Address { st ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Conceal the Froala editor when blur events occur

Currently, I am utilizing Forala with the specific setting: initOnClick: true, Everything is running smoothly, but is there a way to accomplish the "opposite" I'm looking to hide the editor upon blur? I have searched through the documentation, but d ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

Using the TypeScript NextPage function along with the getInitialProps static method and @typescript-eslint/unbound-method

After enabling typescript-eslint with its recommended settings, I encountered an issue in my code. I came across this helpful post on Stack Overflow: Using getInitialProps in Next.js with TypeScript const X: NextPage = props => {/*...*/} X.getInitialP ...

implementing the reuse of form control names for multiple dropdowns in an Angular application

When using the dropdown menu, I am facing an issue where selecting a value from the second dropdown makes it disappear. This is because both dropdowns are using the same formControlName to pass values to the backend with the same header. How can this be fi ...

Dropdown Pattern with React CTA Modal

While using MaterialUI's ButtonGroup for a dropdown menu, I encountered an issue trying to set up a series of CTAs that are easily interchangeable within it. The goal is to have all components reusable and the choices in the dropdown dynamic. const C ...

Angular 7 - Personalized Name for Formbuilder's Dynamic Form

Currently, I am developing a form builder with Angular: return this.fb.group( { myaccount: [ '', [Validators.required]] } ); When an error message is thrown for an element, I iterate through the form controls and disp ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Spring Boot + Angular: missing required parameter is causing an issue

When working on my project, I encountered an issue with sending a POST request from the client side in Angular to a server based on Spring Boot. Here is the code snippet I used: const headers = new HttpHeaders().set( "Content-Type", "app ...

Utilizing the useState hook with generics in React for efficient data management

Utilizing a unique react hook designed to manage input validation for text fields and checkboxes, adaptable to both string and boolean values through the use of generics. An error is encountered when attempting to assign a value using setValue, displaying ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

The Dilemma of using forRoot() in Angular 2/4+ Shared Modules

After uncovering the treasure that is forRoot() while delving deeper into Angular dependency injection (DI), I find myself pondering on the best practices for its usage. I came across this method when trying to enable a lazy loaded module to access a serv ...

In Angular, when using multiple-selection mode in mat selection, the Error Value should always be in the form of

**Everything is working fine except for one error in the console. How can I remove this error? Can anyone please help me? Save, Edit, and searching are working perfectly fine. ** public campaignCategoryFormGroup$: FormGroup = this.fb.group({ // 'c ...

Looking to utilize Axios in React to make API calls based on different categories upon clicking - how can I achieve this?

My current issue involves making an API call upon clicking, but all I see in my console is null. My goal is to have different API categories called depending on which item is clicked. const [category, setCategory] = useState(""); useEffect(() => { ...

When running the command "ionic capacitor run android", the task of compiling debugJavaWithJavac failed in the capacitor app

After successfully creating an Ionic 6.19.1 application, I incorporated the variables.gradle file and ran the "ionic capacitor run android" command without any issues. Here are the variable details: ext { minSdkVersion = 26 compileSdkVersion = 30 ...

Combining Typescript and React to create a conditional callback prop type depending on whether an optional prop is

In my react component, I have the option to pass an optional prop called isSingle (boolean) and a required prop called onSelect (callback). If the isSingle prop is used, I want the callback to have a different signature. type CustomProps<T> = { ...

Angular - struggling to properly sort incoming data based on property with getter and setter functions

Within my application, there exists an array of objects containing a boolean property that is subject to change. Whenever this property changes, I use the .next(changedData) method to emit the updated array to the component that is subscribed. The compone ...