Developing a front-end Angular application with a back-end C# API to handle posting of form data, including files

Seeking assistance with understanding how to upload a file (FormData) and an object from Angular to C# API. It seems that the HttpClient post method can only accept one body parameter, so I am unable to post both the FormData object and the SomeObject object simultaneously. I attempted encapsulating the SomeObject in FormData using FormData.append, but without success.

Below is a snippet of the Angular frontend code:

uploadAttachment(abcId: number, someObject: SomeObject)
{
  const url = this.apiUrl + '/abc/' + abcId;

  const formData = new FormData();
  formData.append('file', fileData);

  return this.http.post<ScopeItemAttachment>(url, formData, 
  {
    reportProgress: true,
    observe: 'events'
  });
}

And here is a snippet of the C# API code:

[HttpPost("{abcID}", Name = "UploadAttachment")]
public IActionResult UploadAttachment(int abcId, SomeObject someObject)
{
    try
    {
        var file = Request.Form.Files[0];
        var temp = Request.Form.Keys;

        if (file.Length > 0)
        {
            fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            MemoryStream ms = new MemoryStream();
            file.CopyTo(ms);

            ms.Close();
            ms.Dispose();

            return Ok();
        }
        else
            return BadRequest(new { message = "File content length must be greater than zero" });
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Internal server error: {ex}");
    }
}

Answer №1

Suppose you have a SomeObject setup like this:

public class SomeObject
{
    public IFormFile File { get; set; }
}
  1. Add the [FromForm] decorator to the request body (someObject).

  2. You can access the file using someObject.File instead of Request.Form.File[0].

[HttpPost("{xyzId}", Name = "UploadAttachment")]
public IActionResult UploadAttachment(int xyzId, [FromForm] SomeObject someObject)
{

    var file = someObject.File;

    ...
}

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

Angular 17 doesn't seem to be correctly implementing *ngIf to hide the div

After spending hours trying to display a div based on certain conditions using *ngIf in Angular, I am still unable to make it work. The following code is not showing the expected result: <div *ngIf="item.billingItem=='Staff'">This ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...

Tips for implementing logic on input values in Angular 4

How to increase a value from a form in app.component.html by 2 and display it <input type="number" class="form-control" [(ngModel)]="value" /> <!-- <p><button (click)="submit()" class="btn btn-warning btn-sm">Submit</button ...

Disabling the last control in a formGroup when sorting an array with Angular

I am facing an issue with sorting an array based on a numeric control value inside a formGroup nested in another array: const toSort = [ ['key2', FormGroup: {controls: {order: 2}}], ['key1', FormGroup: {controls: {order: 1}}] ] ...

Adding a dynamic index from ngFor to an HTML attribute value can be accomplished by incorporating the current

I am using ngFor and I am trying to make an attribute inside the loop change its value by adding the ngFor index. This means that each div created within ngFor will have a unique attribute value. Source: <div class="class1" *ngFor="let item of items; l ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

An exception has occurred in the format

I have a function that looks like this /// /// This function is used to populate the emplist drop down for mentor users. /// private void BindEmpDropDownForMentor() { string strSelectMentorQuery = "SELECT FIRST_NAME + ...

Discovering all routes and categories of a JSON using System.Text.Json in .NET 6

I've created a method to retrieve all combinations of Path + Type for every key in a JSON using the JSON.NET library: public static IEnumerable<string> GetKeys(this JToken jToken) { var keys = new List<string>(); var jTokenKey = $ ...

Show Firebase data on Angular 6 mat-card in a randomized sequence when the page loads or refreshes

Is it possible to display cards in a random order when the value of a form changes or when the page is refreshed, while fetching data from Firebase? Below is my Component Template: <ng-container *ngFor="let geoToDisplay of geosToDisplay | async"> ...

Can you please verify the most recent updates for Bootstrap and Syncfusion in my Angular project?

Could someone help me figure out when the bootstrap and syncfusion libraries were last updated in my Angular project? I'm having difficulty finding this information. ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

What is the process for transforming every data type within an array?

My problem involves handling various types of data type ParseMustaches<T extends string[], U extends Record<string, string> = {}> = T extends `{{${infer U}}}` ? Record<U, string> : never type Test = ParseMustaches<[" ...

Struggling to retrieve local JSON file in Angular 5 - facing relentless 404 error

I've scoured every available article and post on this topic, yet I am still unable to pinpoint where I am making a mistake with this seemingly simple task. (Particularly, following this example.) It seems like I am missing something obvious, but after ...

Excluding specific patches with TargetedPatchingOptOut and applying additional attributes to abstract methods

Do attributes like TargetedPatchingOptOut get inherited by classes during optimization, even if they are not handled by the framework? For example: public abstract class TestBase { [TargetedPatchingOptOut("Optimize across boundaries")] public ab ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...

Angular5 - Modify a public variable using an intercept in a static service

Take into account the following Angular service: @Injectable() export class AuthService { public userConnected: UserManageInfo; getManageInfo(): Observable<UserManageInfo> { return this.httpClient .get('api/Account/Man ...

Angular: Issue with setting a new value in child component on the second attempt via @Input directive

Implementing a child component to manage a dropdown feature. The parent component includes a reset button to revert the user's selection in the dropdown (child component) back to 'None'. Check out the code link here. app.component.html: ...

Is it possible to toggle between namespace and class using parentheses?

While working with older javascript code, I stumbled upon the following snippet: // module1.js class Class { constructor() { console.log('hello') } } const exported = { Class: Class, } module.exports = exported This code is then ...

Retrieving Twitter profile information using C#

In my C# app, I am allowing users to input their name and then retrieve their profile data from Twitter without the use of an API. The URL I am currently using is: The response I receive is a JSON message like this. {"id":184937673,"id_str":"184937673"," ...

What is the best way to invoke a class function within a static object?

Here's an example for you: export class MyClass { myString: string; constructor(s: string) { this.myString = s; } myFunction() { return "hello " + this.myString; } } export class MainComponent { static object1: MyClass = JSON. ...