Having trouble retrieving image information within the Asp.net core controller

I am facing an issue trying to store image details in the database through Angular and ASP.NET Core. I am unable to retrieve the image data sent from Angular in the controller. Although I am able to obtain the image information using the [FromForm] attribute in the controller parameter, my goal is to have it stored inside the model itself. Any insights would be appreciated.

Here is the Model in Asp.net core

public class FileModel
{
    public FileModel()
    {
        SpouseDetails = new SpouseDetailsData();
        ChildrensDetails = new List<ChildrensDetailsDataModel>();
    }
    public IFormFile? Photo { get; set; }
    //public byte[]? PhotoData { get; set; }
    public int UserDetailId { get; set; }
    public List<ChildrensDetailsDataModel>? ChildrensDetails { get; set; }
    public SpouseDetailsData SpouseDetails { get; set; }
    public class ChildrensDetailsDataModel
    {
        public string ChildCountry { get; set; } = null!;
        public string ChildCity { get; set; } = null!;
        public string ChildState { get; set; } = null!;
        public string ChildPhoneNumber { get; set; } = null!;
        public DateTime ChildDOB { get; set; }
        public string ChildLastName { get; set; }
        public string ChildEmailAddress { get; set; } = null!;
        public string ChildFirstName { get; set; } = null!;
    }
    public class SpouseDetailsData
    {
        public string SpouseEmail { get; set; } = null!;
        public string? SpouseCity { get; set; }
        public string? SpouseState { get; set; }
        public string? SpouseCountry { get; set; }
        public string SpouseHometown { get; set; } = null!;
        public string SpouseFirstName { get; set; } = null!;
        public string SpouseLastName { get; set; } = null!;
        public DateTime SpouseDob { get; set; }
    }
}

This is the Angular code

   composeModel(): void {
    this.updateUserModel.firstName = this.profileForm.value.firstName;
    this.updateUserModel.lastName = this.profileForm.value.lastName;
    this.updateUserModel.socialMedia = this.profileForm.value.firstName;
    this.updateUserModel.state = this.profileForm.value.state;
    this.updateUserModel.dob = this.profileForm.value.DOB;
    this.updateUserModel.city = this.profileForm.value.city;
    //Spouse Details
    this.updateUserModel.spouseDetails = this.spouseDetails;
    this.updateUserModel.photoData=this.selectedFile;
    this.updateUserModel.childrensDetails =  this.profileForm.value.childrensDetails;
  }

Angular Model

    export class UserDetailModel {
    childrensDetails: ChildrensDetailsModel[]=[];
    spouseDetails!: SpouseDetails
    id:string="";
    photoData!:File;
    photo!:FormData
}

This is the Controller

 [HttpPost]
    [Route("UpdateUser")]
    public async Task<JsonResult> UpdateUser([FromBody] FileModel userDetailModel)
    {
        var userslist = await _userBusiness.UpdateUser(userDetailModel);
        return new JsonResult(new { userslist });
    }

Service file in angular

  updateUser(userDetailModel:any):Observable<any> {
    return this.http.post<any>(`${UserProfileURLConstants.USER_PROFILE}`,userDetailModel);
}

Answer №1

If you want to send a file along with additional data from your Angular frontend to the API backend, one way to do it is by using the FormData object. You can populate the form data with the necessary values and then have your backend action method retrieve these values using the [FromForm] attribute.

const formData = new FormData();
formData.append('Photo', selectedFile);
formData.append('SpouseDetails.SpouseEmail', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3b2a3c3b0f2a372e223f232a612c2022">[email protected]</a>');
formData.append('SpouseDetails.SpouseCity', 'blabla..');
// console.log(formData);
this.http
  .post<any>('{url_here}', formData)
  .subscribe((data) => {
    //...

https://i.sstatic.net/3uoLx.png

Additionally, if you need to send photo files along with data in the request body, you can consider using FileReader.readAsDataURL() to obtain a base64-encoded string. This string can then be converted into a byte array within the backend action method.

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

What is the best way to find the clinic that matches the chosen province?

Whenever I try to choose a province from the dropdown menu in order to view clinics located within that province, an error 'TypeError: termSearch.toLowerCase is not a function' pops up. This part of the code seems confusing to me and any kind of ...

Steps for displaying a loader after refreshing data using queryClient.invalidateQueries:1. Utilize the query

I am currently working on a project where I need to redirect to a specific page after updating an item. While the code is functioning correctly, I have encountered an issue with the loader not displaying. export const useUpdateStatusArchiveSurvey = () => ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

What is the best way to include the number 7 and other lower numbers in an array?

I am facing an issue where I need to retrieve all the months that have passed in 2020, such as January, February, March, April, May, June, July, and August, and store them in an array. After executing the code below, my variable 'month' returns ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

What is the most effective way to extract necessary data and attributes from XML code?

Working with angular, I am receiving an XML response from a call to my API. Specifically, I need to extract the name attribute of the bpmn:task property from the XML. <bpmn:process> <bpmn:task Id= "Loopin809" name="Process 1" > <bpmn:Incom ...

Testing the Observable StatusChanges in Angular Forms: A Step-by-Step Guide

My Angular component has a unique feature where it takes an NgForm as an input and emits an object when the form becomes valid after modification. @Input() form!: IQuestionForm; //this type extends NgForm; @Input() question!: IQuestion; @Output() questionC ...

Steps for mandating the specification of a type parameter for a generic React component

When setting up a new instance of a generic React component, I noticed that the TypeScript type checker automatically defaults to unknown without requiring me to specify the type argument: https://i.sstatic.net/1hT6H.png Ideally, I would prefer if TypeSc ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

"Handling dependency injection with cyclic dependencies along with a custom implementation of HTTP and ConfigService

I am currently working on implementing a ConfigService to retrieve the appropriate configuration for each environment within the project. However, I have run into an issue with cyclic dependencies. (index):28 Error: (SystemJS) Provider parse errors: C ...

Can you explain the significance of the 'project' within the parserOptions in the .eslintrc.js file?

Initially, I struggle with speaking English. Apologies for the inconvenience :( Currently, I am using ESLint in Visual Studio Code and delving into studying Nest.js. I find it difficult to grasp the 'project' setting within the parserOptions sec ...

Tips for transferring information between service functions in Angular

In my front-end development, I am working on creating a store() function that adds a new question to the database. However, I need to include the active user's ID in the question data before sending it to the back-end. Below is the code for the store ...

Utilizing TypeScript to export a class constructor as a named function

Imagine you have this custom class: export class PerformActionClass<TEntity> { constructor(entity: TEntity) { } } You can use it in your code like this: new PerformActionClass<Person>(myPersonObject); However, you may want a more co ...

Ways to increase the size of a div to match the maximum height of its parent container

My current project involves using an angular dialog layout where the API to open and manage the dialog comes from a separate library. The dialog's parent container has a max-height attribute, meaning the dialog's height is determined by its conte ...

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

An issue was encountered in the karma/config.tpl.ts file at line 13, column 18 - a TS1109 error indicating that an expression was expected. This

I'm encountering the following error after updating to Angular 9, so I haven't downgraded TypeScript. Could someone please assist me? I've tried numerous solutions without success. node_modules/karma/config.tpl.ts:66:16 - error TS1005: &apo ...

The Ngrx selector fails to activate when the reducer modifies the portion

In my Angular 2 application, I heavily utilize Ngrx stores which have proven to be extremely beneficial. I have a well-structured system in place for my stores where I use selectors to retrieve specific parts of the state. Normally, all the selectors work ...

Find out whether the page was reloaded or accessed directly through a hyperlink

I need to find out if the page was accessed directly via a link. If it was, I need to perform a certain action. However, my current implementation is not working as intended, as even a page refresh triggers this action. Is there an alternative method to ch ...