[英]Send Nested JSON with file in HttpClient C#
I want to send this object to the server:我想将此 object 发送到服务器:
public class Product
{
public string name { get; set; }
public string description { get; set; }
public ICollection<Photo> photos { get; set; }
}
This object have a collection of other objects:这个 object 有一个其他对象的集合:
public class Photo
{
public string url { get; set; }
public IFormFile file { get; set; }
public string description { get; set; }
}
How can I send the Product
object with its collection of Photo
objects?如何发送带有Photo
对象集合的Product
object? and How can I send a file in the Photo
object?(I want to use application/json
not form-data
)以及如何在Photo
object 中发送文件?(我想使用application/json
而不是form-data
)
You should send the file contents as a Base64 string您应该将文件内容作为 Base64 字符串发送
Create the string like this像这样创建字符串
Byte[] bytes = File.ReadAllBytes("path\\to\\file.jpg");
String 64string = Convert.ToBase64String(bytes);
Then just update your photo class to have a string for the file, as assign it然后只需更新您的照片 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, ..... }
Of course this assumes that your server expect this and can decode accordingly.当然,这假设您的服务器期望这一点并且可以相应地解码。 I assume you also are writing the server side code.我假设您也在编写服务器端代码。
You can convert it back like this:您可以像这样将其转换回来:
Byte[] bytes = Convert.FromBase64String(64string );
File.WriteAllBytes("path\\to\\file.jpg", bytes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.