Home > Software engineering >  How can I Extract JSON Object that Holds Base64 and File Extension from application/json body in ASP
How can I Extract JSON Object that Holds Base64 and File Extension from application/json body in ASP

Time:04-04

I am passing a JSON object that holds 2 Keys from React to ASP.NET Core as Follows

formData = { image: "Base64String Here", type: "JPEG" }

       url,
       method: "POST",
       data: {image: formData.image, type: formData.type},
       headers: {
         'Content-Type': 'application/json'
       }
        })

it is then collected in my controller as follows

 public async Task<ActionResult<IEnumerable<AppImage>>> UploadImage()
        {
            string jsonString;
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                jsonString = await reader.ReadToEndAsync();
            }
            try
            {
                await using var transaction = await _context.Database.BeginTransactionAsync();

                SQLAppImage sqlData = new SQLAppImage(_context);
                ImageHelper ih = new ImageHelper(_configuration);

                //String filePath = ih.UploadImage(image, type);

                //AppImage appImage = new AppImage
                //{
                //    ImagePath = filePath,
                //    FileType = type
                //};

                //sqlData.Add(appImage);
                await transaction.CommitAsync();
                return Ok();
                
            }
            catch (Exception e)
            {

                throw e;

            }

        }

but i cannot seem to get the JSON object through, is there any recommendations that you might have that can help me please

Thank you in Advance

CodePudding user response:

To do this, create a class as shown below :

public class UploadPhotoDto
{
    public string Image { get; set; }
    public string Type { get; set; }
}

and use it as your method input Like This:

[HttpPost]
public async Task<ActionResult<IEnumerable<AppImage>>>UploadImage(UploadPhotoDto uploadPhotoDto)
{
   //And you can access them
    string base64 = uploadPhotoDto.Image;
    string type = uploadPhotoDto.Type;

    //Your Code 
}
  • Related