Tips for transferring an excel file to a C# controller from Angular 4 within Visual Studio 2017

I'm working on a web application where I need to import an Excel file and send it to the server-side controller.

On the server-side, I am utilizing EPPlus for this task.

Can anyone provide guidance on how to accomplish this?

I would greatly appreciate any help in achieving this goal.

Answer №1

Add a file input field to your template

<input type="file" #fileInput />
<button (click)="uploadFile();">Upload</button>

Next, navigate to your component

@ViewChild('fileInput') fileInput;
// import httpclient from @angular/common/http
...
public uploadFile(): void {
   if (this.fileInput.files.length === 0) {
      return; // additional validation may be needed
   }

   const formData = new FormData();
   formData.append('file', this.fileInput.files[0]);
   this.http.post('http://my-url/api/my-endpoint', formData).subscribe(...); // standard procedure
}

Now, create an endpoint in your API like this

[HttpPost]
// the parameter here must be named 'file' to match the formdata key
public IActionResult UploadFile([FromBody] IFormFile file)
{
    // based on your requirements, you can save it to the filesystem or store it in the database as a byte array
}

If you specify where the file should be saved, I can provide further C# code. However, this is the general process of receiving files from the front-end in your back-end.

Answer №2

There are a variety of options available for uploading files, whether it be through third-party components or examples...

You can also find numerous resources and samples on how to handle file uploads server-side...

  • asp.net - How to upload file with web-api
  • A Guide to Uploading Files In ASP.NET MVC 5
  • And More.

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

The error being thrown at line 538 in the module.js file is causing issues when using

I encountered an error in my Angular 4 project that says "module.js:538 throw err;". Can anyone provide insight on what this means? module.js:538 throw err; ^ Error: Cannot find module 'swagger-js-codegen' at Function.Module._resolveFilena ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Utilizing the String Enum for mapping an interface with an index

Using Typescript, I aim to make use of my string enumeration: export const enum MutationKeys { registerUser = 'registration/REGISTER', registerUserCompleted = 'registration/REGISTER_COMPLETED' } This allows the string values t ...

What is causing the error message "Module '@reduxjs/toolkit' or its type declarations are not found" to appear?

Although I have a good understanding of React-Redux, I decided to delve into TypeScript for further practice. Following the recommended approach from the react-redux team, I created a new project using the TS template: "npx degit reduxjs/redux-templa ...

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

What are the steps to get started with AngularJS 2?

When starting an Angular 1.XX project, we typically use the following code to bootstrap: ng-app ="myApp" Then in our Javascript file, we set up our app like so: var app = angular.module('myApp',[]); But how do we go about bootstrapping in Ang ...

Testing the receiveMessage function in SQS using Jest unit tests

Struggling to find the right approach for unit testing this function. I almost have it, but can't quite nail it down. Take a look at the function below: receiveMessage(callback: Function): any { this.sqs.receiveMessage( this.params, ...

An issue with the HTTP GET Request method is that it often sends "?" instead of "/"

I have a general method for interacting with my Swagger API: get<ReturnType>(url: string, params?: HttpParams): Observable<ReturnType> { return this.http.get<ReturnType>(environment.apiUrl + url, { params: params, }); } ...

Error encountered in Azure Pipelines build task: Failure due to requirement for initialization

When I directly invoke index.js using node, everything works fine. However, when running the Mocha tests, the task fails with a "Must initialize" error message. This is how my tasks index.ts code looks like: import * as path from "path"; import tl = requ ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Converting Large XLSX File (over 600MB) to CSV Using Node.js

Currently, I am facing an issue with converting a large XLSX file, which is over 600mb in size, to CSV format. The conversion process works perfectly fine with smaller files that are less than 3MB. However, when it comes to larger files, the program star ...

Why does TypeScript include a question mark next to the argument when GraphQL specifies it as nullable true?

// image.entity.ts import { Field, ObjectType } from '@nestjs/graphql'; import { Column, DeleteDateColumn, Entity, PrimaryGeneratedColumn, } from 'typeorm'; @ObjectType() @Entity() export class ImageEntity { @PrimaryGenerate ...

Dealing with 400 Bad Request Error Handling in Angular 6 when communicating with WebApi (using HttpClient)

Here is an Asp.net Core WebAPI that handles bad requests by providing error details when a duplicate user attempts to register. public async Task<IActionResult> Register([FromBody] RegisterModel registerModel) { if (ModelState.IsValid) ...

Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items. Here is my HTML code: <ion-header> <ion-toolbar> <ion-title>recipes</ion-title> </ion-toolba ...

Arranging and categorizing information from an Array

In my array of data called history, the elements are sorted and ordered by creation day. I want to display not only the sorted data but also the elements' creation time Additionally, I want to include a group for "created in the last hour" ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: https://i.sstatic.net/Ah70f.png I ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

Cannot execute loop

I'm currently working on creating a loop within my component that involves making server calls: getBeds() { this.patientService.getBeds(this.selectedWard).subscribe( result => { console.log(result); this.beds = result; this.getBedDet ...

Tips for managing 'single click' and 'double click' events on a specific html element in typescript:Angular 2 or 4

My problem lies in the fact that both events are activated when I double click. For instance, I want distinct functionality to occur for each event trigger. <a (click)="method1()" (dblclick)="method2()"> Unfortunately, both method1() and method2() ...