【发布时间】:2021-02-17 23:18:25
【问题描述】:
我正在尝试通过我的网络服务将图像文件上传为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);
但在上述情况下,我收到以下错误:
【问题讨论】:
-
直接把图片文件放到project里才能得到图片的流。如果您确实想实现它,则需要将图像放入本地或 sd 卡。检查stackoverflow.com/questions/54663101/…。
-
@LucasZhang-MSFT 是否可以将流转换为
System.Net.Http.HttpContent?我需要通过服务传递该格式的数据。 -
你想用httpclient上传图片流吗?
-
从这里获得解决方案:forums.xamarin.com/discussion/186014/…
-
@LucasZhang-MSFT 是的,我正在尝试上传图片
标签: xamarin.forms shared-project