.NET Core backend experiences file becoming null during Angular multipart upload

I am having some issues while attempting to upload a basic file to my backend dotnet core application. The problem is that the file ends up being null, whereas the description is not.

This is my .NET Core controller:

[AllowAnonymous]
[HttpPost]
[Route("upload")]
public async Task<IActionResult> ImageUpload(IFormFile file, [FromQuery] string description)
{
    if (file == null)
    {
        return BadRequest("Failed to upload file");
    }

    // The file always turns out to be null!

    return Ok("Good!");
}

And here is an excerpt from my Angular code for uploading the file:

async upload(file: File, description: string = '') {
  if (file) {
    const formData = new FormData();
    formData.append('file', file, file.name);
    return await this.http.post(route('image', 'upload'), formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      params: { description },
      responseType: "text"
    }).toPromise();
  } else {
    return Promise.resolve('');
  }
}

Answer №1

To send data from Angular, use the FormData() object and set a description using the .append() method to the fd object in the service method. All the appended data will be accessible in the API using the Request object with Request.Form.

API

 [HttpPost("SaveProfilePic")]
public ResponseResult SaveProfilePic(IFormFile files)
{
 var file = Request.Form.Files[0];
 var form = Request.Form;
}

Angular

<form (ngSubmit)="Save(f)" #f="ngForm">
<input type="file" name="profile_pic" (change)="setProfilePic($event)">
<input type="submit" value="submit" />
</form>
Save(form)
{
 this.MyService.SaveProfilePic(this.profile_pic, 'description').subscribe(res => {

 })
}
    setProfilePic(event:any)
    {
     if (event.target.files && event.target.files[0]) {
     this.profile_pic = event.target.files[0];
     var reader = new FileReader();
     reader.readAsDataURL(event.target.files[0]); // read file as data url
     reader.onload = (event:any) => { // called once readAsDataURL is completed
     }

     }
    }

MyService

public SaveProfilePic(picture: File,fileName): any {
 const fd = new FormData();
 fd.append('image', picture, fileName);
 return this._http.post(this.url + 'MyController/SaveProfilePic', fd);
}

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

Oops! An issue has occurred: "The formControlName is required to be used alongside a parent formGroup directive." This error pertains to the following input field: <input ngbDatepicker #e="ngbDatepicker" (click)="e.toggle()">

I've set up a date picker with an input field and pop-up following the instructions found here: This is what I have: 1) The necessary imports are all in the template: <input id="field_completed" [(ngModel)]="endDate" type="text" class="form-cont ...

Exploring the discrepancies in utilizing the i18n library versus directly incorporating locale from JSON in vue.js

Recently, I decided to incorporate Chinese language into my Vue app. To achieve this, I loaded the entire JSON text into Vuex and utilized the stored text directly, instead of relying on an i18n library. I'm curious to know if there are any potential ...

Create a fresh date object using Angular 2

Hello, I am having some issues with filling out a form. I want the date field to automatically populate with the current date, and for the user to be able to view it but not edit it. I attempted to do this, but unfortunately, it did not work as expected. ...

Angular 2 - What is the latest method for bootstrapping correctly?

I am looking to integrate Angular 2's security features, particularly CSRF, which requires the use of the XSRFStrategy provider. However, the current bootstrap process I am using is not up to date to support this provider. This leads to the challenge ...

What is the reason behind TypeScript not being able to recognize the value from the context wrapper?

I'm currently working on implementing a context wrapper. My goal is to pass the state variables as provider values and then access those values by using useContext in the ToolBar component. type NavContextType = { isDrawerOpen: boolean; setIsD ...

Route user based on login status using router

I want to set up automatic routing to a login page for users who are not logged in. app.module.ts import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from &ap ...

Issue with Importing 'tiny-secp256k1' Library in Jest with Typescript

I have recently integrated the npm package tiny-secp256k1 into my project. This package offers non-default exports of various functions, each with type declaration included. Despite multiple attempts to import it and run my test suite using Jest, I keep ...

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

Getting an error with TypeScript and React refs: Cannot access property 'current' when it's undefined

I am currently developing a React application using TypeScript. One of the features I want to implement is a button that scrolls to a specific header in a child component on the main page. To achieve this, I have created a reference in the child componen ...

The code encountered an error with message TS2345 stating that the argument type '(a: Test, b: Test) => boolean | 1' cannot be assigned to a parameter type of '(a: Test, b: Test) => number'

Apologies for the lengthy subject, but I am having trouble understanding the response. Here is my code snippet: this.rezerwacjeFilteredByseaarchInput.sort(function (a, b) { if (a[5]===null) { // console.log(a[5]); return 1; } ...

Tips for designing a navbar specific to a profile section

I am currently working on an angular application with a navigation bar composed of anchor tags. When the user logs in, I have an ngIf directive to display my profile icon with dropdown options. However, I am facing challenges in styling it correctly. I aim ...

Guide on integrating an Angular 10 Component into a cell in Ag-Grid

I am currently working with an Angular10 component, specifically a toggle switch, that I need to integrate into a specific column within my ag-grid cell. Currently, I am using a basic HTML checkbox in the following manner: colDefs: ColDef[] = [ { fiel ...

Acquiring a JQuery object within Angular: A step-by-step guide

Please review the code snippet below: protected get myModalDialogRef(): JQuery { return $('#myModalDialog'); } What dependencies do I need to install in order to specify JQuery as the return type? I noticed in the package.json file, there i ...

Modifying the background color of a card or div in Angular2 when it is

I have a display of items in the form of cards: <div class="mdl-grid"> <div class="mdl-cell mdl-cell--2-col"> <div class="goal-list-card" *ngFor="let goal of core_goals| values; let j = index;"> <div class="car ...

What are the steps for implementing function composition or pipelines with a multi-parameter function?

During a recent interview, I was tasked with retrieving data from the jsonplaceholder /posts and /comments endpoints and creating a function to match comments with posts where comment.postId == post.id, then constructing a unified JSON object containing ea ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

Error: Attempting to access the 'tokenType' property of an undefined object is not allowed

We encountered an error while attempting to embed a report using the Power BI Angular library. TypeError: Cannot read properties of undefined (reading 'tokenType') at isSaaSEmbedWithAADToken (reportEmbed?navContentPaneEnabled=false&uid=am ...

Using a predefined list of text entries, deduce a type or structure that accurately defines the dictionary, utilizing string literals to represent the various values within

My scenario involves a static dictionary: const myDict = { 1: "one", 2: "two" } The default inferred type in this case is Record<1 | 2, string>. I am seeking to create a type that exclusively accepts the exact string literal ...

The attribute 'getValue' is not a valid property for the data type 'Subject<boolean>'

Currently, I am working with Angular2 and have a BehaviorSubject. isOpen$: Subject<boolean> = new BehaviorSubject<boolean>(true); When I try to retrieve the latest value using: isOpen$.getValue() It functions correctly, however, there is a ...

The element is implicitly assigned an 'any' type due to the fact that a 'string' expression cannot be used to access data in the 'ProductMapData' type

In my sortDynamic function, I am attempting to dynamically sort data like this: const sortDynamic = (key: string, order: string) => { const sortOrder = order === 'asc' ? 1 : -1; return (a: ProductMapData, b: ProductMapData) => { ...