0

我正在尝试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);

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

在此处输入图像描述

4

1 回答 1

1

如果要使用 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);
于 2020-11-05T10:35:31.387 回答