Search code examples
maui

MAUI: Issue with uploading project's local image to database via post API as ByteArrayContent - System.ArgumentNullException


I have added a few avatar images on the project folder named Avatars and set its Build Action to Embedded Resource.

I added it for profile image update for the user. I need to upload the selected image to our database using a POST API. Below is the code I am using:

try
{
    if (isAvatar)
    {
        string avatarFileName = "MyProjectName.Avatars." + selectedAvatar;
        var assembly = typeof(RESTServices).GetTypeInfo().Assembly;
        var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{avatarFileName}");
        var streamContent = new StreamContent(stream);
        content.Add(streamContent, "file", avatarFileName);
    }
}
catch (Exception exc)
{
    System.Diagnostics.Debug.WriteLine("AvatarException:>" + exc);
}

But I am getting the below exception:

AvatarException:>System.ArgumentNullException: Value cannot be null. (Parameter 'content')
   at System.ArgumentNullException.Throw(String paramName)
   at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName)
   at System.Net.Http.StreamContent..ctor(Stream content)
   at ProjectName.RESTServices.SaveProfile(String jsonData, String applicationId, String siteId, FileResult photo, ByteArrayContent cameraByteContents, String cameraPicPath, String selectedAvatar, Boolean isGallery, Boolean isCamera, Boolean isAvatar) in E:\My Projects\MAUI
eedhelp-app-maui\ProjectName\RESTServices.cs:line 1004

The exception is on the below line:

var streamContent = new StreamContent(stream);

The image folder is on the project's root folder. Check the below screenshot:

enter image description here

Is there any mistake on the path of the selected avatar image and due to that this null issue is showing?


Solution

  • Please set the image's Build Action to the MauiAsset in the Avatars folder, then read it by using var stream = await FileSystem.OpenAppPackageFileAsync("Avatars\\"+ selectedAvatar);

     using var stream = await FileSystem.OpenAppPackageFileAsync("Avatars\\"+ selectedAvatar);
     MemoryStream ms = new MemoryStream();
     stream.CopyTo(ms);
     ms.Position = 0;    
     StreamContent streamContent = new StreamContent(ms);
    
     //you can detect the streamContent is not null by the length
     var length= streamContent.Headers.ContentLength;