Search code examples
c#emailhttpresponsemime

Http Response Contains MIME stream.. which has binary Images seperated by Boundary String.. need to get those Images and save using c#


when i make a HTTP request to the server it responses with the MIME Response Stream which has two or more images in it as Binary data which are separated by Boundary String Now i need to extract those images only and save them individually into database

Stream Looks like this...

Header has

RETS-Version: RETS/1.0

MIME-Version: 1.0

Content-type: multipart/parallel;

boundary="simple boundary"

Http ResoinseStream Has

--simple boundary

Content-Type: image/jpeg

Content-ID: 123456

Object-ID: 1

<binary data>(Image1)

--simple boundary

Content-Type: image/jpeg

Content-ID: 123457

Object-ID: 1

<binary data>(Image2)

--simple boundary --

I need to extract image1 and image2 and save those in database as binary image.


Solution

  • If you use my MimeKit library, you can do this really easily:

    static MimeEntity ParseHttpWebResponse (HttpWebResponse response)
    {
        var contentType = ContentType.Parse (response.ContentType);
    
        return MimeEntity.Parse (contentType, response.GetResponseStream ());
    }
    
    static void SaveAllImages (HttpWebResponse response)
    {
        var entity = ParseHttpWebResponse (response);
        var multipart = entity as Multipart;
    
        if (multipart != null) {
            foreach (var image in multipart.OfType<MimePart> ()) {
                using (var memory = new MemoryStream ()) {
                    image.ContentObject.DecodeTo (memory);
    
                    var blob = memory.ToArray ();
    
                    // save it to your database
                }
            }
        }
    }