简体   繁体   中英

Send Nested JSON with file in HttpClient C#

I want to send this object to the server:

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:

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? and How can I send a file in the Photo object?(I want to use application/json not form-data )

You should send the file contents as a Base64 string

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM