【发布时间】:2016-05-12 12:05:58
【问题描述】:
我们正在读取文件的字节数组并将其转换为base64字符串,如下所示
public static string ZipToBase64()
{
FileUpload fileCONTENT = FindControl("FileUploadControl") as FileUpload;
byte[] byteArr = fileCONTENT.FileBytes;
return Convert.ToBase64String(byteArr);
}
string attachmentBytes = ZipToBase64();
string json1 = "{ \"fileName\": \"Ch01.pdf\", \"data\": " + "\"" + attachmentBytes + "\"}";
当我们尝试将最大 1 GB 的大文件转换为 base64 字符串时,它会抛出内存不足异常。我们正在将此 json 发送到 restful wcf 服务。以下是我在 RESTful WCF 服务中的方法。
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void UploadFile1(Stream input)
{
string UserName = HttpContext.Current.Request.Headers["UserName"];
string Password = Sql.ToString(HttpContext.Current.Request.Headers["Password"]);
string sDevideID = Sql.ToString(HttpContext.Current.Request.Headers["DeviceID"]);
string Version = string.Empty;
if (validateUser(UserName, Password, Version, sDevideID) == Guid.Empty)
{
SplendidError.SystemWarning(new StackTrace(true).GetFrame(0), "Invalid username or password for " + UserName);
throw (new Exception("Invalid username or password for " + UserName));
}
string sRequest = String.Empty;
using (StreamReader stmRequest = new StreamReader(input, System.Text.Encoding.UTF8))
{
sRequest = stmRequest.ReadToEnd();
}
// http://weblogs.asp.net/hajan/archive/2010/07/23/javascriptserializer-dictionary-to-json-serialization-and-deserialization.aspx
JavaScriptSerializer json = new JavaScriptSerializer();
// 12/12/2014 Paul. No reason to limit the Json result.
json.MaxJsonLength = int.MaxValue;
Dictionary<string, string> dict = json.Deserialize<Dictionary<string, string>>(sRequest);
string base64String = dict["data"];
string fileName = dict["fileName"];
byte[] fileBytes = Convert.FromBase64String(base64String);
Stream stream = new MemoryStream(fileBytes);
//FileStream fs1 = stream as FileStream;
string networkPath = WebConfigurationManager.AppSettings["NetWorkPath"];
File.WriteAllBytes(networkPath + "/" + fileName, fileBytes); // Requires System.IO
}
请提供大字节数组转base64字符串的解决方案
【问题讨论】:
-
将 1GB base64 编码的字符串作为 json 发送不是一个好主意,你不觉得吗?
-
@Evk 感谢您的评论。我们正在使用 android 移动应用程序和 Web 应用程序来上传文件。我们正在文件系统上的远程服务器上上传文件。这就是为什么我编写了用于上传文件的 RESTFul wcf 服务
-
但我的意思是——如果你的文件很大(超过 10MB)——你永远不应该通过 json 序列化它们。您必须以流式方式在请求正文中传递它们。对于 RESTful wcf 服务也是如此。我本可以展示如何将 byte[] 逐块转换为 base64,但这不会帮助你。
-
@Evk 是的,我们在同一页上。我已将 json 以流式方式传递给 WCF 服务。我已经更新了我的问题。请参见。请提供base64字符串中逐块转换字节数组的解决方案
标签: c# asp.net base64 bytearray chunks