如何通过chunck字节数组将chunck转换为base64字符串?
我们正在阅读文件的字节数组,并将其转换成字符串的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
使用流输入的事实在WCF服务并不真正意味着你传递流的方式提供任何解决方案。事实上在你的情况下,你不这样做,因为:
- 你在内存中的客户端缓冲整个文件来建立json字符串。
- 您通过
stmRequest.ReadToEnd()
将整个文件缓冲在内存中的服务器上。
所以不会发生流式传输。首先你应该认识到这里不需要json - 你只需要在你的http请求体中传递文件即可。你应该做的首先是扔掉下面的安全检查所有代码在你UploadFile1
方法,而是这样做:
public void UploadFile1(string fileName, Stream input) {
// check your security headers here
string networkPath = WebConfigurationManager.AppSettings["NetWorkPath"];
using (var fs = File.Create(networkPath + "/" + fileName)) {
input.CopyTo(fs);
}
}
在这里,我们只是没有任何缓冲复制输入流输出流(文件)(当然CopyTo
将缓冲大块,但它们会很小)。马克您的服务方法:
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile1/{fileName}")]
为了使您在查询字符串传递的文件名。
现在到客户端。不确定您使用哪种方法与服务器进行通信,我将使用原始HttpWebRequest显示示例。
var filePath = "path to your zip file here";
var file = new FileInfo(filePath);
// pass file name in query string
var request = (HttpWebRequest)WebRequest.Create("http://YourServiceUrl/UploadFile1/" + file.Name);
request.Method = "POST";
// set content length
request.ContentLength = file.Length;
// stream file to server
using (var fs = File.OpenRead(file.FullName)) {
using (var body = request.GetRequestStream()) {
fs.CopyTo(body);
}
}
// ensure no errors
request.GetResponse().Dispose();
我在编译wcf服务时遇到错误。使用'UriTemplate'的端点不能与'System.ServiceModel.Description.WebScriptEnablingBehavior'一起使用。 –
请参阅:https://blogs.msdn.microsoft.com/justinjsmith/2008/02/15/enablewebscript-uritemplate-and-http-methods/。如果没有什么帮助 - 在头中传递文件名而不是查询字符串。我实际上讨厌WCF,因为那些出现在各处的小问题并没有多年使用它(并且从未回头)。 – Evk
我已经通过头文件中的文件名。 –
发送1GB base64编码字符串作为json不是一个好主意,你不觉得吗? – Evk
@Evk感谢您的评论。我们正在使用android移动应用程序和Web应用程序来上传文件。我们正在文件系统上的远程服务器上传文件。这就是为什么我写了RESTFul wcf服务上传文件 –
但我的意思是 - 如果你的文件很大(比10MB多) - 你不应该在json中将它们序列化。你必须以流式传递的方式在请求正文中传递它们。对于RESTful wcf服务也是如此。我本来可以展示如何通过块将byte []块转换为base64,但这不会帮助你。 – Evk