2015-07-20 91 views
2

我有一些base64存储在数据库(实际上是图像),需要上传到第三方。我想使用内存上传它们,而不是将它们保存为图像,然后将其发布到服务器。有没有人知道如何将base64转换为流?如何将base64值从数据库转换为C#流#

我怎样才能改变此代码:

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

改为使用图像文件的base64解释来填充StreamContent对象。

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; 
    } 
+1

http://stackoverflow.com/questions/351126/convert-a-string-to-stream和StreamContent将接受甲流,这并不一定是一个文件,你应该能够把它交给最终的小河去从那里。 – Hammerstein

回答

2

你会想要做这样的事情,一旦你已经得到了来自数据库的字符串:

var bytes = Convert.FromBase64String(base64encodedstring); 
var contents = new StreamContent(new MemoryStream(bytes)); 
// Whatever else needs to be done here. 
+0

这是我需要的。谢谢willaien –

1

只是作为一个替代办法,这与大的流效果很好(节省中间的字节数组):

// using System.Security.Cryptography 
// and assumes the input stream is b64Stream 
var stream = new CryptoStream(b64Stream, new FromBase64Transform(), CryptoStreamMode.Read); 
return new StreamContent(stream);