我在名为 Avatars 的项目文件夹中添加了一些头像图像,并将其
Build Action
设置为 Embedded Resource
。
我添加它是为了用户的个人资料图像更新。我需要使用 POST API 将所选图像上传到我们的数据库。以下是我正在使用的代码:
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);
}
但我遇到以下异常:
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
例外情况在下面一行:
var streamContent = new StreamContent(stream);
图像文件夹位于项目的根文件夹中。检查下面的截图:
所选头像图像的路径是否有任何错误并因此显示此空问题?
请将图片的
Build Action
设置为Avatars文件夹中的MauiAsset
,然后使用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;