Search code examples
angularasp.net-core

Unable to pass the byte data from angular with Uint8Array


I have my model as follows

public class TimeSheetManagerModel
{
    public string EmailId { get; set; } = string.Empty;
    public string EmployeeName { get; set; } = string.Empty;
    public int Month { get; set; }
    public int Year { get; set; }
    public byte[] FileData { get; set; }
}

I have created following in typescript

export class managerModel {
    employeeName: string;
    emailId: string;
    month: number;
    year: number;
    fileData: Uint8Array;

    constructor() {
        this.employeeName = "";
        this.emailId = "";
        this.month = 0;
        this.year = 0;
        this.fileData = new Uint8Array()
    }
}

This is my code

const payload = new managerModel();
this.handleExport().then((arrayBuffer) => {
if (arrayBuffer)
payload.fileData = new Uint8Array(arrayBuffer);
payload.employeeName = this.updateModel.employeeName;
payload.emailId = this.updateModel.employeeEmailId;
payload.month = this.selectedDate.getMonth();
payload.year = this.selectedDate.getFullYear();

console.log('Payload before sending:', JSON.stringify(payload));
this.timeSheetService.nofityManager(payload)

I am seeing this in my console but in my C# code I am seeing it as NULL so not sure what is going wrong

enter image description here

This is my code

nofityManager(managerModel: managerModel): Observable<any> {
        return this.configService.getBaseUrl().pipe(
            switchMap((baseUrl: string) => {
                const url = `${baseUrl}/NotifyManager`;
                const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
                return this.http.post<any>(url, managerModel, { headers });
            })
        );
    }

This is my server side call

public async Task<bool> NotifyManager(TimeSheetManagerModel timeSheetManagerModel) { }

Solution

  • Post the data with file via FormData instead of JSON request body.

    let formData = new FormData();
    
    formData.append('fileData', new Blob([arrayBuffer]));
    formData.append('employeeName', managerModel.employeeName);
    formData.append('emailId', managerModel.emailId);
    formData.append('month', managerModel.month);
    formData.append('year', managerModel.year);
    
    return this.http.post<any>(url, formData);
    

    Since you are sending the data as form data, your API action should expect to receive data in form data with [FromForm] attribute.

    public async Task<bool> NotifyManager([FromForm] TimeSheetManagerModel timeSheetManagerModel)
    

    Besides, use the IFormFile instead of byte[] type for the FileData property.

    public class TimeSheetManagerModel
    {
        ...
    
        public byte[] FileData { get; set; }
    }