How to upload files using Angular 4

Having some trouble trying to upload a file using angular 4, even after closely following a tutorial. I'm not sure where I might be going wrong, so any help in spotting the issue would be greatly appreciated. Here is the code snippet:

import { Component, OnInit } from '@angular/core';
import { ConnectionManagerComponent } from 'src/app/connection-manager/connection-manager.component';
import { ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { Validators } from '@angular/forms';

@Component({
  selector: 'app-new-contact-list.component',
  templateUrl: './new-contact-list.component.html',
  styleUrls: ['./new-contact-list.component.css']
})
export class NewContactListComponent implements OnInit {
  @ViewChild(ConnectionManagerComponent) connectionManager:ConnectionManagerComponent;
  form:FormGroup;
  selectedFile: File;

  onFileChanged(event) {
    this.selectedFile = event.target.files[0]
  }

  constructor(private fb: FormBuilder,public router:Router) {
    this.form = this.fb.group({
      name: ['', Validators.required],
      fileName: ['', Validators.required],


  });
  }

  ngOnInit() {
  }
  addContactList()
  {
    const val = this.form.value;
    let contactListName = val.name;
    const fd = new FormData();
    fd.append("name" ,contactListName);
    fd.append('file', this.selectedFile,this.selectedFile.name);
    console.log(fd);
    this.connectionManager.post('/contactGroups', res => {
      console.log(res);
           this.router.navigateByUrl('/newContactList');
       },fd);
  }

}
 <div class="input-group">
   <input style="display: none" id="fileName" 
          formControlName="fileName"
          type="file"
          (change)="onFileChanged($event)"
          #fileInput>
   <button (click)="fileInput.click()">Select File</button>
 </div>

Answer №1

It seems that only file selection is occurring in this section. The execution halts at the onFileChanged() function. You can try using the code snippet provided below for the onFileChanged() function. If it does not work as expected, please include a reference for further assistance.

onFileChanged(event) {
this.selectedFile = event.target.files[0];
addContactList();
}

Answer №2

How to Upload Files in Angular:

Within the app.component.html file, add the following code:

<input #fileUpload type="file" id="fileUpload" style="" (change)="detectFiles($event)" (click)="fileUpload.value = null">

In the app.component.ts file, include the following TypeScript code:

import { Component } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private fileUploadService: FileUploadService) {

  }
  detectFiles(event) {
    if (event.target.files.length == 0) {
      console.log("No file selected!");
      return
    }
    let file: File = event.target.files[0];
    console.log("FILE DATA:",file);

    let uploadPath = "/home/upload/";

  this.fileUploadService.uploadFile(uploadPath, file).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Response:
          console.log(event.body);
      }
    });

  }
}

To properly configure file uploads, make changes in the app.module.ts file as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

import { HttpClientModule } from '@angular/common/http';
import { FileUploadService } from './fileUpload.service';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpClientModule],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ FileUploadService ]
})
export class AppModule { }

Lastly, create a fileUpload.service.ts file and add the following code for handling file upload requests:

import { Inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpRequest } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class FileUploadService {
  constructor(private http: HttpClient) {

  }

  uploadFile(uploadPath, fileToUpload: File) {
    const _formData = new FormData();
    _formData.append('file', fileToUpload, fileToUpload.name);
    _formData.append('uploadPath', uploadPath);

    const url = `api/v1/uploadFile`;

    const request = new HttpRequest('POST', url, _formData, {reportProgress: true });
    return this.http.request(request);
  }

}

For more information and a working example, visit this link.

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

Verify if there is a cookie available; then execute the load() function. If the cookie matches, it is necessary to

$(document).ready(function() { var hrefs = { "en": ["includes/test1.html", "includes/test2.html"], "es": ["includes/test3.html", "includes/test4.html"] } $(function() { var cookie = Cookies.get('langCookie'); if (cookie) { ...

Presenting a fully equipped GLTF model prior to incorporating it into the environment

I've been experimenting with different methods to accomplish this task: I'm looking to load a model and then have the function return it. var loader = new THREE.GLTFLoader(); loader.crossOrigin = true; var loadedModel = loader.load('model. ...

Matching HTML tags with Regex while excluding specific ones is possible using a carefully

My goal is to strip out all HTML opening/closing tags (along with attributes) that are not on my approved list. const allowedTags = ['a', 'b', 'i', 's', 'u', 'sup', 'sub', 'strong&a ...

canvas resolution adjustments

I've created a unique function that can transform text into an image by following this reference: Convert Text to Image using javascript <canvas id='textCanvas' height=20></canvas> <img id='image'> <br> < ...

Unexpected type error being thrown by Typescript

Despite having successfully executed this code multiple times in the past, I am now perplexed as to why it is not working as expected. While I acknowledge that the types are not being inferred, this particular error rarely occurs. Could it be due to a mist ...

Methods for opening ngx-daterangepicker-material outside of a button/icon when there are multiple date range pickers in the same form

Is there a way to open ngx-daterangepicker-material by clicking outside of any button or icon? I am aware that ngx-daterangepicker-material allows this functionality through the use of @ViewChild(DaterangepickerDirective, { static: false }) pickerDirective ...

Tips for observing the return value of a function in JavaScript

When dealing with an object in a browser, each property has a getter and setter that can be overridden in order to monitor the attribute. But what about the return value of a function? In AngularJS, we can use 'ng-show' to control the visibility ...

The getelementbyid function can only target and retrieve the information from the first ID within a PHP

I am facing an issue with a form embedded in a PHP while loop and processed by JavaScript using getelementbyid. When I submit the form, it only submits the first item on the loop. Below is my PHP code: $qsel = "SELECT * FROM sellbusiness ORDER BY sn DESC ...

Encountering issues with connecting to the MongoDB server through Node.js

When working with MongoDB in Python, everything runs smoothly without any errors. However, when using Node.js, an error keeps popping up. Can someone please guide me on how to resolve this issue? jdcaovuwqxoqppwwqmjcawpwuaciwowjqwqhpaiwdoqi Below is the ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

I continue to encounter an error every time I attempt to place an HTML nested div on a separate line

When I structure the HTML like this, I don't encounter any errors: <div class="game-card"><div class="flipped"></div></div> However, if I format it differently, I receive an error message saying - Cannot set property 'vi ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

Deleting the HTML element

Can someone assist me with my script issue? I am facing a problem: when I open my file on fullscreen (over 768px), and move my pointer around the logo div, nothing happens. However, if I resize my browser to below 768px, then back again above 768px, the ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Deleting a row from a table using TypeScript in Angular

I am currently working on a task management application and I am facing an issue with deleting a row when clicking the delete button. Below is the table structure in my HTML: <table *ngFor="let todo of todos; let i = index;" class="todo ...

Identifying the Type of Element Based on Its Identifier

I have a function in JavaScript called testElement() that is triggered by the onclick event. <script type = "text/javascript"> function testElementType(element){ var elemId = $(element).attr("id"); //Can I determine the ' ...

Failure to display updated property value

After rendering an array of objects, I am attempting to add a new property using a function. However, the new property value is not displaying on the page even though it is present when I log the object in the console. The new property that I want to add ...

javascript doesn't execute the php script

Hello everyone, I've been working on a project for quite some time and I’ve encountered an issue that I can't seem to solve. Hopefully, you can help me out with this. I have a digital LED strip controlled by an Arduino, which in turn is control ...

What could be causing the issue with multiple selection in jQuery?

I am interested in implementing multiple selection on my ASP page. I came across the pickList jQuery plugin and followed the instructions provided at the following link: Below is a snippet from my ASP page: <%@ Page Language="C#" AutoEventWireup="true ...