从InputStream读的base64数据文件C# [英] Read base64 data from InputStream to file C#

查看:190
本文介绍了从InputStream读的base64数据文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序从剪贴板中获取图像,并将其保存到服务器上。
得到的图像是通过Java和JavaScript完成。
我的aspx codebehind接收该数据的(Base64),并写入到文件。
这里是我的code

my application gets image from clipboard and saves it to server. getting image is done through java and javascript. my aspx codebehind receives this data (base64) and writes to file. here is my code

  byte[] buffer = new byte[Request.InputStream.Length];
    int offset = 0;
    int cnt = 0;
    while ((cnt = Request.InputStream.Read(buffer, offset, 10)) > 0)
    {
        offset += cnt;
    }
    fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string base64 = System.Text.Encoding.UTF8.GetString(buffer);

    byte[] bytes = Convert.FromBase64String(base64);
    System.IO.FileStream stream = new FileStream(@"D:\www\images\" + fileName, FileMode.CreateNew);
    System.IO.BinaryWriter writer =new BinaryWriter(stream);
    writer.Write(bytes, 0, bytes.Length);
    writer.Close(); 

我的问题是BASE64。我得到这个字符串作为UTF8 EN codeD。看来这篡改形象,我不能够打开或查看它们。

my problem is base64 . i get this string as utf8 encoded. seems this tampers the image and i am not able to open or view them.


下面是创建数据的Java code

Here is the java code that creates the data

StringBuffer sb = new StringBuffer();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
sb.append("data:image/").append("png").append(";base64,").append(Base64.encode(stream.toByteArray()));

所以我会得到一个像这样的字符串
数据:图像/ PNG; BASE64,iVBORw0KGgoA ..
并用ajax我这个字符串张贴到我的aspx页面

so i will get a string like this data:image/png;base64,iVBORw0KGgoA.. and using ajax i posts this string to my aspx page

推荐答案

您应该删除数据:图像/ PNG; BASE64, preFIX当你阅读的base64 解码之前输入流。例如,你可以在拆分

You should remove the data:image/png;base64, prefix when you read the input stream before base64 decoding. For example you could split at the ,:

byte[] buffer = new byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, buffer.Length);
string data = Encoding.Default.GetString(buffer);
string[] tokens = data.Split(',');
if (tokens.Length > 1)
{
    byte[] image = Convert.FromBase64String(tokens[1]);
    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string path = Path.Combine(@"D:\www\images", fileName);
    File.WriteAllBytes(path, image);
}

这篇关于从InputStream读的base64数据文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆