Add an image to a directory with Angular 7

I am having trouble uploading an Image to the assets/ folder using Angular 7. Below is my attempted solution:

HTML:

<form [formGroup]="form" (ngSubmit)="postData()" class="intro-form-css">
              <div class="form-row">
                <div class="form-group col-lg-12 col-md-12 col-12">
                    <label class="form-text">Icon</label>
                  <input type="file" class="file" #introIcon id="uploadBtn" (change)="onFileChange($event)" name="browseIcon">
                  <div class="input-group">
                    <span class="input-group-btn">
                      <button class="btn btn-css-browse" type="button" (click)="triggerFile()">Browse</button>
                    </span>
                    <input type="text" class="form-control css-input" disabled placeholder="Upload Icon" #uploadFileName id="uploadFile">
                  </div>
                </div>
              </div>
              <div class="form-row">
                <div class="form-group col-lg-12 col-md-12 col-12">
                  <label class="form-text">Title</label>
                  <input type="text" formControlName="introTitle" placeholder="Enter Title" class="form-control border-radius-0" />
                </div>
              </div>

              <div class="form-row">
                  <div class="form-group col-lg-12 col-md-12 col-12">
                    <label class="form-text">Description</label>
                    <textarea rows="5" cols="50" formControlName="introDesc" placeholder="Enter Description" class="form-control border-radius-0 no-resize"></textarea>
                  </div>
                </div>
              <div class="form-row">
                <div class="form-group col-lg-6 col-md-6 col-6">
                  <button type="button" class="btn btn-block custom-css-btn" >Submit</button>
                </div>
                <div class="form-group col-lg-6 col-md-6 col-6">
                  <button type="button" class="btn btn-block custom-css-btn" >Cancel</button>
                </div>
              </div>
            </form>

ts:

      fileName;
      fileType;
      form: FormGroup;

      @ViewChild('introIcon') uploadFileVariable: ElementRef;
      @ViewChild('uploadFileName') uploadFileName: ElementRef;
      ngOnInit() {
          this.form = this.formBuilder.group({
            browseIcon: [''],
            introTitle: '',
            introDecs: ''
          });
        }

        triggerFile(){
          document.getElementById('uploadBtn').click()
        }

        onFileChange(event) {
          if (event.target.files.length > 0) {
            const file = event.target.files[0];
            this.fileName = file.name;
            this.fileType = file.type;
            if(this.fileType == 'image/png' || this.fileType == 'image/jpeg' || this.fileType == 'image/PNG' || this.fileType == 'image/JPEG') {
              let fName = (<HTMLSelectElement>document.getElementById('uploadFile')).value;
              fName = this.fileName;
              this.uploadFileName.nativeElement.value = fName;
              this.form.get('browseIcon').setValue(file);
            } else {
console.log('Error!');
            }
          }
        }

        postData() {
          const formData = new FormData();
          if (this.form.get('browseIcon').value == '' || this.form.get('browseIcon').value == null) {
console.log('Error!');
          } else {
            formData.append('file', this.form.get('browseIcon').value);
            formData.append('introDecs', this.form.get('introDecs').value);
            formData.append('introTitle', this.form.get('introTitle').value);
            console.log('formData:', formData);
          }
        }

I am struggling to determine where and how to include code to upload the image to a local folder. Additionally, I am not receiving any response in the formData. My goal is to also send the file name, title, and description to a web-service.

Answer №1

Uploading files from the frontend, such as Angular or JavaScript, is not achievable.

It is not possible to use JavaScript to pinpoint a user's Desktop location for file downloads.

To accomplish file uploads, consider creating an API on the backend using technologies like Node.js, PHP, or Java. Send your image using formData to the API and save the file in the designated location.

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

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Securing Your Angular 2 Application with UI-Router Authentication

Currently, I am working on implementing JWT authentication within my Angular 4 project. The backend setup is complete, but there are still some additional tasks to be done on the front end. During my research, I came across the auth0/angular2-jwt library. ...

Is it possible to retrieve the signature for every method within a class?

Let's consider a scenario where we have a class defined as follows: class Actions { static FooAction = 'foo' as const; someAction1() { return { type: Actions.FooAction, payload: {a: 1, b:2} }} static BarAction = &apos ...

Showing user input in an Angular 2 component based on their selection in a dropdown menu

Inside a div element, there is a select tag which contains two options - New and Used. Following this are two div elements within a separate container that should be hidden based on whether New or Used is selected. Take a look at my code below and let me ...

Can you provide any instances of Angular2 projects with intricate routing, specifically with version 2.0.0-rc.1?

Currently, I am in the process of building a web application with angular2 (2.0.0 rc 1) and encountering obstacles due to the insufficient documentation, especially when it comes to establishing intricate routing. Since version 2.0.0 was just released app ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...

The ReactJS Material Table Tree mode experiences delays when new row data is introduced

My Reactjs app utilizes the material-table widget within a component: render() { return ( <div> <Row> <MaterialTable title="Mon équipement" style={{ width: "100%", margin: "0%" }} ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Steps to handle Angular's response to an HTTP 401 error

I am using nodejs (express) as a server side and angular 6 as the client. On the server, I have a middleware function that checks for a session. If the session is invalid or does not exist, I want to send a response to the client so it can handle it accord ...

An error of unknown token U was encountered in the JSON data starting at position 0

I am facing an issue with my MEAN Stack development. Currently, I have an Angular Form set up with proper values to create a company in the database using Node Express on the backend. However, I keep encountering an error stating that the JSON in Node is ...

Adding attributes to parent DOM elements of a component in Angular2: A Step-by-Step Guide

I'm working with the following code: ... <div class="container"> <div class="fancy"> <fancybutton></fancybutton> </div> <button (click)="addAttribute()">Remove</button> <button (click)="remAttr ...

Sending an array from one page to another using Angular 2

I am currently working on a weather application using Angular. As a beginner in Angular, I am facing an issue with sending data to the second page to display the weather information of the selected city. Can someone please help me identify where the proble ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Using ts-node-dev (and ts-node) with ECMAScript exports and modules

Currently, we are in the process of upgrading TypeScript to a more modern standard due to changes in libraries like nanoid that no longer support commonjs exports. Our goal is to integrate the ts-node-dev library with exporting to ECMAScript modules. The ...

Angular 4 - Nested Dropdown Menu with Submenus (Multiple Levels)

Just diving into Angular 4 development and have a specific requirement. Seeking guidance on the optimal approach to implement the following. Looking to add a Dropdown menu to the header of my website. Clicking on the Dropdown menu image should reveal a me ...

Top method for obtaining base64 encoding of an image in Angular or Node.js

Looking to obtain Base64 data for images. Currently utilizing Angular 6 on the frontend and NodeJS on the backend. Should I extract the Base64 string on the frontend or is it better to handle conversion on the backend before returning it to the frontend? ...

Setting the current day on mat-datepicker can be easily done by using the appropriate

Is there a way to automatically set the date picker on the current date when the user opens the dialog box? Additionally, I want to add validation in Code_personnel that checks if it has exactly 4 characters. What type of validation attributes should I us ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

Tips on ensuring JSON object structure with type and interface in an Angular application

In my angular project, I have created a router config file to handle routing efficiently. This config file contains JSON data like this: router.config.ts { branch:{ list:'/app/branch/list', add:'/app/branch/add' }, ...