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

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image. I have managed to achieve this using ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

The NGX countdown timer is experiencing a discrepancy when the 'leftTime' parameter exceeds 24 hours, causing it to not count down accurately

When the leftTime configuration exceeds 864000, the timer does not start from a value greater than 24 hours. <countdown [config]="{leftTime: `864000`}"></countdown> For example: 1. When leftTime is set to `864000`, the Timer counts down from ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Why is my ASP.NET Core Crud request failing with incorrect method matching?

I am facing an issue with the third method in my Angular ASP.NET Core Controller. The first two methods work fine, but the GetBookItemsByTitle does not seem to be firing correctly. As I am still learning, I believe my mistake here is obvious. /// <summ ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Error in Angular 2.0 final version: Unable to access the 'injector' property of null object

Upon transitioning from Angular 2 RC5 to 2.0 Final, I've encountered some errors while running my tests. It's puzzling me as to what could be causing this issue. TypeError: Cannot read property 'injector' of null at TestBed._create ...

How to Retrieve Input Field Value Using Cypress Custom Command

Is there a way to retrieve the value of an input[text] element within a custom command? Cypress.Commands.add('extendValue', { prevSubject: 'element' }, (subject: JQuery<HTMLElement>, extension: string): any => { const r ...

Is there a resource or extension available for identifying design flaws in Typescript code?

Currently, I am in the midst of an Angular project and am eager to identify any design flaws in my Typescript code. Are there any tools or extensions available that can help me pinpoint these design issues within my project? Any assistance would be greatl ...

Firebase: No user record exists for this identifier. It is possible that the user has been removed from the system

Utilizing Ionic2/Angular2 along with AngularFire2 and Firebase for user authentication during login. Upon successful registration of a user using email & password, I am able to log in with that same email & password without any issues. public fireAuth: ...

Vite HMR causes Vue component to exceed the maximum number of recursive updates

After making changes to a nested component in Vue and saving it, I noticed that the Vite HMR kept reloading the component, resulting in a warning from Vue: Maximum recursive updates exceeded... Check out the online demo on stackblitz. Make a change in Chi ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

What strategies should be employed when creating e2e tests that require a specific order of execution?

In the process of developing e2e tests for our angular app using Cypress.io, we are encountering a challenge. While we understand that tests should ideally not rely on each other, it seems challenging to avoid in a practical application. Consider a user ne ...

Using the Ternary Operator in JavaScript to Dynamically Update HTML Elements with Angular

Is there a way to convert the code below into a ternary operator so that it can be used in an .HTML file? statusChange && statusChange === 'Employed' ? true : employmentStatus === 'Employed'; To clarify, I want to assign the re ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

Can anyone provide a webpack configuration to package a webpack plugin together?

I'm in the process of developing a webpack plugin using typescript. Before I can publish it on NPM, I need to bundle the plugin code. However, I've encountered an exception stating that my plugin class is not a constructor. Below is the director ...

Methods for showing Internet Explorer not supported in Angular without needing to import polyfills

Due to the deprecation of IE in Angular 12, I need to inform users to switch to a supported browser by displaying a static warning on my page. To achieve this, I have implemented a simple snippet in the index.html file that appends a CSS class to the body ...

The Angular material datepicker fails to organize items in a horizontal row

My web application features an Angular Material datepicker, however, I am facing an issue where not all elements are showing up in a row. The view is as follows: Datepicker To prevent any custom CSS from impacting the view, I have removed all customized ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...