Uploading files using Angular 2 and TypeScript

I am currently developing an Angular 2 project, where I need to upload a file and send some parameters from the client to the server (Spring Rest Server). I have attempted to use the FormData Interface for this purpose. However, when I try to append a file (created from event.srcElement.files) to it and then log the object to the console, it displays an empty FormData object. On the server side, I am using @requestparam("file") to retrieve the file. Any assistance on this matter would be greatly appreciated.

Here is the code in my HTML file:

<input type="file" #uploadFile multiple="true" (change)="uploadFile($event)"/>

The component file looks like this:

  uploadFile(event:any){
    let file = event.target.files[0];
    let fileName = file.name;
    console.log(file)
    console.log(fileName)
    let formData = new FormData();
    formData.append('file',file);
    this.examService.uploadAnswer(formData);
}

And in the service file:

uploadAnswer(formData:FormData){  
            console.log(formData)
            this.http.post(this.url+'/uploadanswer', formData)
            .map((response: Response) => {
                let res = response.json();
            Object.keys(res).forEach(name =>
                this.questions=res[name]
            );
            });

Answer №1

Here is the correct way to structure your HTML:

<input id="file-field" name="file-field" (change)="uploadFile($event)" type="file" accept=".png,.jpg,.jpeg">

This function will capture the file in the component:

uploadFile(event) {
  let files = event.target.files;
  if (files.length > 0) {
    console.log(file); // File will be displayed
    this.service.uploadFile(file);
  }
}

And in the service:

uploadFile(file) {
  let formData: FormData = new FormData();
  formData.append('file', file, file.name);

  this.http.post(url, formData, request_options)
}

This will result in the file being sent with the 'file' key in the request data.

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

Revise: Anticipated output missing at conclusion of arrow function

Here is the code snippet that I am having trouble with: <DetailsBox title={t('catalogPage.componentDetails.specs.used')}> {component?.projects.map(project => { projectList?.map(name => { if (project.id === name.id) { ...

Conceal Columns in DevExtreme with Angular2 EditMode

Is there a way to conceal a DataGrid Column while in EditMode by utilizing DevExtreme and Angular2? <h3>Test</h3> <dx-data-grid id="gridContainer" [dataSource]="xxx" [allowColumnReordering]="true" [allowColumnResizing]="true" [rowAltern ...

The HAProxy is encountering difficulties when trying to connect to port 80 for the Angular application that is currently running on

I currently have an Angular application running on port 4200, and I have implemented HAProxy as a reverse proxy to redirect all traffic from port 80 to 4200. However, while my HAProxy settings are correctly directing traffic from 8080 to 4200, the redire ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Retrieving data from .NET API in Angular

I'm currently developing a project using Angular 7 and .NET Core. I’m facing an issue with passing file contents from a .NET API to Angular. Here's my API code: public async Task<IActionResult> GetLicenseInformation() { try { ...

Is there a way to disable or reassign the ctrl + left click shortcut in Visual Studio Code?

Is there a way to disable or change the Ctrl + left click function in Visual Studio Code? I find that I accidentally trigger it about 20% of the time when selecting text with my mouse, and it interrupts my workflow. Any suggestions on how to fix this issue ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

MockStore has not been configured as a provider

My current challenge involves testing my app.component using Cypress. This component is supposed to fetch data from the ngrx store, and I've made sure to refer to the official documentation for guidance on setting up the test. Here's how the test ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Encountered an issue with the core-js postinstall script, causing a failure

I encountered the following errors while attempting to install node modules in an existing Angular project. The installation is being carried out on a Windows machine (Win32 X64). > [email protected] postinstall node_modules\babel-runti ...

Display an array depending on the value in Angular 2 when clicked

In my current Angular 2 project, I am dealing with a .json file structured like this: { "PropertyName": "Occupation", "DefaultPromptText": "occupation text", "ValuePromptText": { "WebDeveloper": "for web developer", "Administra ...

How to navigate to an anchor tag on a separate page using Angular 9

Is there a way in Angular 9 to create a link that directs to a specific section on a page like I would in plain HTML using <a href="myPage#mySection">go to my section</a>? I've come across outdated solutions when searching for this, so I&a ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Modify the selected toggle buttons' color by utilizing the MUI ThemeProvider

I am currently working on customizing the color of selected toggle buttons within my React app using TypeScript and ThemeProvider from @mui/material 5.11.13. Despite my efforts, when a toggle button is selected, it still retains the default color #1976d2, ...

Encountering a issue while attempting to sign up for a function within the ngOnInit lifecycle

I keep encountering the error message "Cannot read property 'name' of undefined" when working with a basic API that returns information about vehicles. The Vehicle object has several fields: public int Id {get ;set;} public int ModelId { ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

Unable to navigate beyond the boundaries of an app

I am currently facing an issue with my authentication service where it redirects to the identity server in case of certain errors. I attempted to achieve this using window.location.href = environment.authCodeFlowIssuer;, however, an error occurred: Ref ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

Angular Express redirect and how to implement it

My SSR response service includes a redirect method along with other functionalities: import { Injectable, Inject } from '@angular/core'; import { Response } from 'express'; import { RESPONSE } from '@nguniversal/express-engine&ap ...

Checking if a date is before another date in MomentJS without considering the

Recently, I've been utilizing momentJS to identify future dates without a specific day. Below is the code I've been working with along with the outcome: moment('09/2010').isBefore(moment().format('MM/YYYY'), 'day') ...