我们正在阅读文件的字节数组,并将其转换成字符串的base64如下如何通过chunck字节数组将chunck转换为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
@Evk感谢您的评论。我们正在使用android移动应用程序和Web应用程序来上传文件。我们正在文件系统上的远程服务器上传文件。这就是为什么我写了RESTFul wcf服务上传文件 –
但我的意思是 - 如果你的文件很大(比10MB多) - 你不应该在json中将它们序列化。你必须以流式传递的方式在请求正文中传递它们。对于RESTful wcf服务也是如此。我本来可以展示如何通过块将byte []块转换为base64,但这不会帮助你。 – Evk