Steps for transferring an uploaded .CSV file to a Web service

I'm exploring the process of sending a file uploaded from the UI (angular) to a .NET web service in order for it to parse a CSV file and create a list of objects.

My current understanding of the logic flow is:

File upload ---> Web Service (parse file) --> Web API ---> Database

Does this seem correct?

What steps am I overlooking in terms of sending the file to the service and then to the API Controller?

HTML:

<input type="file" (change)="onFileSelected($event)">
<button type="submit" (click)="onUpload"   class="button">Upload</button>

Web service:

static void Main(string[] args)
{
    string currentDirectory = Directory.GetCurrentDirectory();
    DirectoryInfo directory = new DirectoryInfo(currentDirectory);
    var fileName = Path.Combine(directory.FullName, "sample-data.csv");
    var fileContents = ReadMonitoredEvent(fileName);
}

public static string ReadFile(string fileName)
{
    using (var reader = new StreamReader(fileName))
    {
        return reader.ReadToEnd();
    }
}

public static List<MonitoredEvent> ReadMonitoredEvent(string fileName)
{
    var monitoredEventResults = new List<MonitoredEvent>();
    // Logic for parsing the CSV file and creating objects...
}

I currently do not have any controller or TypeScript code implemented.

My goal is to enable a user-uploaded file to ultimately result in all created objects being stored in the database.

Answer №1

Your approach seems mostly correct, but instead of using a web service, we utilize Http Client in Angular. I recommend checking out a tutorial like this one for more guidance.

UPDATE:

Here is the code snippet for uploading a file to a web API using C#:

[HttpPost]
[Route("File/Post")]
public IHttpActionResult UploadFile()
{
   var httpRequest = HttpContext.Current.Request;
   var postedFile = httpRequest.Files["File"];
   // Add your parsing logic here
   return Ok();
}

And here is the Angular part of the process:

postFile(fileToUpload: File) {
   const formData: FormData = new FormData();
   const tmpUrl=myUrl+"File/Post";
   formData.append("File", fileToUpload, fileToUpload.name);
   return this.http.post(tmpUrl, formData).pipe();
}

I've simplified it for you, but this should help kickstart your progress.

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

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Equalizing Lists in Angular 2

Struggling to locate documentation on this topic, but in Angular 1 it was possible to achieve the following: <textarea ng-model="name" ng-list=","></textarea> With this setup, if you were to input "Hello, world!" into the textarea, the name v ...

npm is unable to install the package called 'node-sass'

So, I'm running a project with npm start and suddenly encountering the same error in multiple components: Module build failed: Error: Cannot find module 'node-sass' Frustrated, I decide to run 'npm install node-sass', only to be ...

PrimeNG - Sticky header feature malfunctioning in the p-table

Hello there, I am currently using PrimeNG p-table which features both horizontal and vertical scrolling. My goal is to implement a sticky header for the table, so far I have attempted two methods: [scrollable]="true" scrollHeight="350px" ...

Include a parameter in a type alias

Utilizing a function from a library with the following type: type QueryFetcher = (query: string, variables?: Record<string, any>) => Promise<QueryResponse> | QueryResponse; I aim to introduce an additional argument to this type without mod ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

What is the process for generating a fresh instance of an Angular service?

Hey there, I've been pondering a solution to a little dilemma I'm facing. Let me share my thoughts and see if you can lend some insight or tell me where I might be going astray. Setting the Stage: In the realm of angular app creation, it's ...

The selected value of the PrimeNG p-checkbox cannot be determined using a function when binding to [ngModel]

These are the rows of my custom p-table <tr> <td>{{user.userName}}</td> <td>{{use.userSurname}}</td> <td *ngFor="let group of groups"><p-checkbox [(ngModel)]="showVal ...

fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Whoops! Looks like the module couldn't be located

After updating my ngx-translate-multi-http-loader from version 8.0.2 to 9.3.1, I encountered a module not found error. The error message is as follows: ./node_modules/ngx-translate-multi-http-loader/fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Err ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

Leveraging WebStorm's TypeScript support in conjunction with node_modules

Attempting to set up a TypeScript project in WebStorm to import a Node.js module has been a struggle. I made sure to download the necessary TypeScript definition in settings and specified --module commonjs in the compiler settings. However, I keep running ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Sorting with lodash in Angular 2

Section: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import * as _ from 'lodash'; @Component({ selector: 'app-ore-table', templateUrl: './ore-table ...

A step-by-step guide on fetching data in List form using LINQ to XML

Looking for assistance with using c# and .net 4.5 Yesterday I asked about how to read an XML file on Stack Overflow. The answer suggested using Descendants() and Elements() to retrieve specific elements from the file. Now, I have an XML file that contain ...

Angular 2: Retrieve current currency rates based on your location

When I apply the {{listing.sellPrice | currency : undefined : 0}} code, it only displays the symbol $. However, I would like for the currency to change based on the user's location. For instance, if someone is in Europe, their currency would be shown ...

Guide to leveraging various build targets while executing the capacitor sync command within an Angular project

In my current Angular project, I have been utilizing Capacitor. Within my angular.json file, I have set up various build targets such as development, staging, and production. To deploy with different configurations, I use the command ng build --configurati ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Ways to reverse bypassSecurityTrustHtml and convert SafeValue to a string

When I generate HTML and insert it into my webpage, I use the following code: let data = '<font color=blue>hello world</font>'; this.safevalue = this.domSanitizer.bypassSecurityTrustHtml(data); In another part of my code, I needed t ...

What is the best way to set up TypeScript interfaces using predefined string literals to limit the possible data types for shared attributes?

In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an erro ...