簡體   English   中英

使用 HttpClient C# 中的文件發送嵌套的 JSON

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM