Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work...

Below is my component where I call my service upon button click:

handleFileInput(file: FileList) {
this.fileToUpload = file.item(0);

const url = 'http://localhost:44328/api/Student';
this.studentService.postFile(this.url, this.fileToUpload)
  .subscribe((res: any) => {
  },
    (err) => {
      if (err.status === 401) {
      } else {
      }
    });

}

Here is the service method used:

 postFile(url: string, fileToUpload: File): Observable<Response> {
    const formData: FormData = new FormData();
    formData.append('File', fileToUpload, fileToUpload.name);
    const headers = new Headers();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    const options = new RequestOptions({ headers });
    return this.http.post(url, formData, options);
}

And here is the controller implementation:

 [Route("/api/[controller]")]
public class StudentController : Controller
{
    private readonly IStudentsService _service;
    public StudentController(IStudentsService service)
    {
        _service = service;
    }

    [HttpPost, DisableRequestSizeLimit]
    public ActionResult UploadFile()
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var httpRequest = HttpContext.Request.Form;//.....
    }
}

However, the request does not seem to be reaching the endpoint. The error message displayed is

POST http://localhost:44328/api/Student net::ERR_CONNECTION_RESET

In the startup.cs file, cors has been added and everything appears to be configured correctly. I am at a loss as to what could be wrong...

startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(x => x.AddProfile(new MappingsProfile()));
        services.AddDbContext<museumContext>(options =>

                  services.AddCors(options =>
        {
            options.AddPolicy("AllowAllOrigins",
                builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
        });

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
        });
        services.AddMvc();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }


        app.UseCors(builder =>
            builder.WithOrigins("http://localhost:44328")
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowCredentials());
        app.UseAuthentication();
        app.UseCors("AllowAllOrigins");
        app.UseMvc();
    }

I'm in need of fresh ideas on how to solve this issue after spending so much time on it.

Answer №1

I encountered a similar situation and found a solution that worked for me.

Here is the code from my upload-view.component.html file:

<div fxLayout="column" fxLayoutAlign="start center" class="update-upload">
    <form id="updateFormHtml" fxLayout="row" fxLayoutAlign="center center" #updateForm="ngForm" (submit)="uploadFile()">
    <div class="file-dropzone">
      <label for="file" class="text">Click here or Drag and Drop file here</label>
      <input id="file" type="file" accept=".json" (change)="setChosenFile($event)" />
    </div>
  </form>
  <div *ngIf="chosenFileName" fxLayout="column" fxLayoutAlign="start center" class="file-info">
    <div class="file-name">{{ chosenFileName }}</div>
    <button form="updateFormHtml" mat-raised-button color="primary">Upload</button>
  </div>
</div>

This is the class included in my upload-view.component.ts file:

export class AdminViewComponent {
  chosenFileName: string;
  chosenFile: any;

  constructor(private snackbar: MatSnackBar, private uploadService: UploadService)   { }

  setChosenFile(fileInput: Event) {
    console.log(fileInput);
    const control: any = fileInput.target;
    if (!control.files || control.length === 0) {
      this.chosenFileName = null;
      this.chosenFile = null;
    } else {
      this.chosenFileName = control.files[0].name;
      this.chosenFile = control.files[0];
    }
  }

  uploadFile() {
    const uploadData = new FormData();
    uploadData.append('file', this.chosenFile, this.chosenFileName);
    console.log(uploadData);

    this.uploadService
        .uploadFile(uploadData)
        .subscribe(
          (response) => {
            this.snackbar.open('File uploaded successfully', null,
            {
              duration: 7000, verticalPosition: 'top',
              horizontalPosition: 'center'
            });
          },
          (error) => {
            this.snackbar.open(error.status, null,
              {
                duration: 7000, verticalPosition: 'top',
                horizontalPosition: 'center'
              });
          }
        );
  }
}

In my upload.service.ts file, I had this method:

public uploadFile(data: any) {
    const url = `${this._baseUrl}/api/script/status`;
    return this.httpClient.post<ActionResponse>(url, data, { headers: new HttpHeaders({
      'Authorization': `Bearer ${this.Token}`
      })
    });
  }

Lastly, here is the corresponding controller method in my .Net Core application:

[HttpPost("upload")]
public IActionResult UploadFile([FromForm(Name ="file")] IFormFile resultFile)
{
    if (resultFile.Length == 0)
        return BadRequest();
    else
    {
        using (StreamReader reader = new StreamReader(resultFile.OpenReadStream()))
        {
            string content = reader.ReadToEnd();
            //Removed code
        }
    }
}

Answer №2

Here is the code snippet to include in your service, following the append step:

const formData: FormData = new FormData();
formData.append('File', fileToUpload, fileToUpload.name);

const uploadReq = new HttpRequest('POST', `url`, formData, {
  reportProgress: true,
});

this.http.request(uploadReq)

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

Attempting to write out a zip file is unsuccessful on Internet Explorer 7

Dealing with an inherited legacy application that securely stores a zip file within a database and must retrieve it, I have encountered a peculiar issue. Everything functions smoothly in Firefox - the zip file can be opened without any problems, and all th ...

Troubleshooting the challenge of transitioning from Angular 4 to Angular 9 with flatMap

In my Angular 4 code, everything runs smoothly: public resolve(): Observable<GridViewDtcConfig> { const permissionResponse = this.flowsService.getPermissions(); return permissionResponse.flatMap((permissions) => { c ...

Issue with Ionic 3 subscribes triggering repeatedly

I've been struggling with the code for an Ionic taxi app for a few weeks now. My main issue is that whenever the page loads, the subscription gets triggered multiple times along with other functions within it. The same problem occurs when any travel i ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...

Easily generate a hierarchical layout in HTML with this straightforward method

I'm currently working on implementing a hierarchical tree structure for a website. I need to organize a user's projects, tasks, and sub-tasks in a visually appealing manner using HTML elements. Any suggestions or creative ideas are welcome! ...

Passing data between Angular 2 components

Below is the component I am working with: @Component({ selector: 'myselector', providers: [ ], directives: [ ChildComponent], pipes: [ ], template: '<myselector>This is {{testEmitter}}</myselector>' }) export cla ...

Creating typed props is important when utilizing the Material UI makeStyles function

Currently, I'm in the process of transitioning some of my React components to the latest makeStyles/useStyles hook API from Material UI. As far as I know, I can still accept classes as a prop from parent components by passing the props to useStyles: ...

Navigate to a different page using the A-g Grid router when a row is

Having trouble making the router link interact with Ag grid. When I use the router link ="url", it always takes me to a different page every time I click on anything in the grid. What I really want is for clicking on an individual row to redirect me to an ...

Code: Ensuring URL spaces are maintained

In my Angular 4 project, I have a service with a delete API that requires two strings as parameters. Here is an example of how it looks: this.http.delete(this.url + 'api/v1/ReportingService/collectionID/'+ '45902' +'/'+' ...

AngularFireFunctions httpCallable doesn't reflect updated data post-response

Despite successfully receiving a value from an Observable using AngularFireFunctions' httpsCallable, the view fails to update even after the http request is completed. In my simple component, I utilize AngularFireFunctions to invoke an httpCallable f ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

RXJS - Trigger a function based on a specific condition being fulfilled by a value emitted from an observable

I have created a search field with autocomplete functionality. By using an observable that monitors changes in the text field, I am able to trigger actions based on user input. this.term.valueChanges .debounceTime(300) .distinctUntilChange ...

Validator for IP addresses in Angular reactive forms

Hey there, I'm currently trying to implement a validator for an IP address in Angular. Strangely, even when I input an invalid IP address like 12.2.2.2..., the GUI indicates it is valid (as shown in the image). However, the console logs reveal that it ...

Learn how to utilize a Library such as 'ngx-doc-viewer2' to preview *.docx and *.xlsx files within the application

After 3 days of searching, I finally found a solution to display my *.docx and *.xlxs files in my angular application. The API returns the files as blobs, so my task was to use that blob to show the file rather than just downloading it using window.open(bl ...

Update my SPFx web component to link to a CSS file instead of embedding the CSS styles directly within the component

I recently developed a web part that is reminiscent of a similar one found on GitHub @ https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-enhanced-list-formatting. This particular web part enables the embedding of custom CSS code directly in ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

Is it possible to use a '.JS' file downloaded through Node Package Manager (npm) directly in a web browser?

Generally, I am looking to utilize a specific library without relying on Node CMD. For instance: I aim to create a TypeScript playground without having to execute 'tsc.cmd' from "npm\node_modules", instead, I want to directly call the tsc c ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Displaying data from a JSON object to a DOM table can be achieved by dynamically generating table columns based on the keys within

There is a JSON object that I'm working with: [ { "SysID": "4", "Defect Classification": "Wrong Image Color", "1": "3.0", "2": "", "3": " ...