我們正在閱讀文件的字節數組,並將其轉換成字符串的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