[英]Send Nested JSON with file in HttpClient C#
我想将此 object 发送到服务器:
public class Product
{
public string name { get; set; }
public string description { get; set; }
public ICollection<Photo> photos { get; set; }
}
这个 object 有一个其他对象的集合:
public class Photo
{
public string url { get; set; }
public IFormFile file { get; set; }
public string description { get; set; }
}
如何发送带有Photo
对象集合的Product
object? 以及如何在Photo
object 中发送文件?(我想使用application/json
而不是form-data
)
您应该将文件内容作为 Base64 字符串发送
像这样创建字符串
Byte[] bytes = File.ReadAllBytes("path\\to\\file.jpg");
String 64string = Convert.ToBase64String(bytes);
然后只需更新您的照片 class 以获得文件的字符串,作为分配它
public class Photo
{
public string url { get; set; }
public String fileContents { get; set; }
public string description { get; set; }
}
Photo p = new Photo() { url = "...", fileContents = 64String, ..... }
当然,这假设您的服务器期望这一点并且可以相应地解码。 我假设您也在编写服务器端代码。
您可以像这样将其转换回来:
Byte[] bytes = Convert.FromBase64String(64string );
File.WriteAllBytes("path\\to\\file.jpg", bytes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.