Xamarin Forms:获取存储在共享项目中的图像文件的路径?

Xamarin Forms: Get the path of an image file stored on the shared project?

我正在尝试通过我的网络服务将图像文件上传为 ByteArrayContent。我已将所有图像添加到共享项目并将构建操作设置为 Embedded resource.

以下是我的代码:

var fileBytes = File.ReadAllBytes("Avatars." + selectedAvatar);
var byteContent = new ByteArrayContent(fileBytes);
content.Add(byteContent, "file", selectedAvatar);

当我像上面那样尝试时,我得到 System.IO.FileNotFoundException: Could not find file "/Projectname.Avatars.ic_avatar01_xx.png"

将图像直接添加到共享项目的文件夹中,如下图所示。

:

我尝试更改 .在文件路径中带有 /,如下所示:

var fileBytes = File.ReadAllBytes("Avatars/" + selectedAvatar);
var byteContent = new ByteArrayContent(fileBytes);
content.Add(byteContent, "file", selectedAvatar);

但在那种情况下,我得到 System.IO.DirectoryNotFoundException: Could not find a part of the path "/Avatars/ic_avatar01_xx.png"

获取存储在共享项目中的图像文件路径的正确方法是什么?

也尝试了另一种方法:

string avatarFileName = "Avatars/" + selectedAvatar;
var assembly = typeof(ProfilePage).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{avatarFileName}");
content.Add(stream, "file", avatarFileName);

但在上述情况下,我收到以下错误:

如果你想使用 Stream 上传图片,可以查看下面的代码

private async Task<string> UploadImage(Stream FileStream)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://your.url.com/");
            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("fileToUpload");
            form.Add(content, "fileToUpload");
            content = new StreamContent(FileStream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = "xxx.png"
            };
            form.Add(content);
            var response = await client.PostAsync("http://your.url.com/", form);
            return response.Content.ReadAsStringAsync().Result;
        }

选项 2:

您也可以使用插件 FileUploaderPlugin 。支持一次上传多个文件

从文件路径上传

CrossFileUploader.Current.UploadFileAsync("<URL HERE>", new FilePathItem("<REQUEST FIELD NAME HERE>","<FILE PATH HERE>"), new Dictionary<string, string>()
            {
               {"<HEADER KEY HERE>" , "<HEADER VALUE HERE>"}
            }
);

选项 3:

MultipartFormDataContent的第一个参数是HttpContent。要处理流,请尝试使用继承自 HttpContent 的 StreamContent 类型。从流中获取 streamContent 并将 id 添加到 MultipartFormDataContent。

string avatarFileName = "Avatars." + selectedAvatar;
var assembly = typeof(ProfilePage).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{avatarFileName}");
var streamContent = new StreamContent(stream);
content.Add(streamContent, "file", avatarFileName);