How to convert base64 value from a database to a stream with C#
Asked Answered
C

3

33

I have some base64 stored in a database (that are actually images) that needs to be uploaded to a third party. I would like to upload them using memory rather than saving them as an image then posting it to a server. Does anyone here know how to convert base64 to a stream?

How can I change this code:

var fileInfo = new FileInfo(fullFilePath); var fileContent = new StreamContent(fileInfo.OpenRead());

to fill the StreamContent object with a base64 interpretation of an image file instead.

    private static StreamContent FileMultiPartBody(string fullFilePath)
    {
        var fileInfo = new FileInfo(fullFilePath);

        var fileContent = new StreamContent(fileInfo.OpenRead());

        // Manually wrap the string values in escaped quotes.
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            FileName = string.Format("\"{0}\"", fileInfo.Name),
            Name = "\"name\"",
        };
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

        return fileContent;
    }
Chicle answered 20/7, 2015 at 19:1 Comment(1)
https://mcmap.net/q/452388/-convert-a-string-to-stream and StreamContent will accept a stream, that doesn't have to be a file, you should be able to hand it the resulting stream and go from there.Stagger
C
68

You'll want to do something like this, once you've gotten the string from the database:

var bytes = Convert.FromBase64String(base64encodedstring);
var contents = new StreamContent(new MemoryStream(bytes));
// Whatever else needs to be done here.
Cameleer answered 20/7, 2015 at 19:18 Comment(0)
A
17

Just as an alternative approach, which works well with large streams (saves the intermediate byte array):

// using System.Security.Cryptography
// and assumes the input stream is b64Stream
var stream = new CryptoStream(b64Stream, new FromBase64Transform(), CryptoStreamMode.Read);
return new StreamContent(stream);
Andantino answered 4/3, 2016 at 11:43 Comment(0)
M
12
var stream = new MemoryStream(Convert.FromBase64String(base64));
Melamine answered 29/5, 2022 at 10:20 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Stephainestephan

© 2022 - 2024 — McMap. All rights reserved.