[英]To append a byte[] to a string in c#
My javascript code sends blobs of data to a handler in C#. 我的JavaScript代码将数据的Blob发送到C#中的处理程序。 My Javascript code is working fine, and I have already tried to receive the data from client(javascript) and pass them to the C# handler and save them in a local Folder.
我的Javascript代码工作正常,并且我已经尝试从client(javascript)接收数据并将它们传递给C#处理程序并将其保存在本地文件夹中。
Instead of saving the data in a folder, I want to now save it in a string
. 现在,我不想将数据保存在文件夹中,而是将其保存在
string
。
My handler each time gets a piece of my information as a byte[]
. 我的处理程序每次都以
byte[]
获取我的信息。
my Javascript: 我的Javascript:
xhr = new XMLHttpRequest();
// this is not the complete code
// I slice my file and push them in var blobs = [];
blobs.push(file.slice(start, end));
while (blob = blobs.shift()) {
xhr.send(blob);
count++;
}
My C# handler: In here, the bool ok
never gets set to true
. 我的C#处理程序:在这里,
bool ok
永远不会设置为true
。 How can I get all my files chunk by chunk as I am sending them from javascript; 从javascript发送文件时,如何逐块获取所有文件; and, instead of saving in a folder, saving it in a string?
并且,而不是保存在文件夹中,而是将其保存在字符串中?
public void ProcessRequest(HttpContext context)
{
try
{
byte[] buffer = new byte[context.Request.ContentLength];
context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);
string fileSize = context.Request.Headers.Get("X_FILE_SIZE");
bool ok = false;
System.Text.StringBuilder myData = new System.Text.StringBuilder();
myData.Append(buffer);
if(myData.Length == int.Parse(fileSize)){ ok=true; }
}
catch (Exception)
{
throw;
}
}
There is no overload of StringBuilder.Append
that takes a byte array, so it will call the StringBuilder.Append(object)
method. 没有使用字节数组的
StringBuilder.Append
重载,因此它将调用StringBuilder.Append(object)
方法。 That will call ToString
on the byte array to get a string value, which results in the string "System.Byte[]"
. 这将在字节数组上调用
ToString
以获取字符串值,这将导致字符串"System.Byte[]"
。
To get the byte array as a string, you need to know what the bytes represent. 要获取字节数组作为字符串,您需要知道字节代表什么。 For example, if the bytes are text that is encoded as UTF-8 then you can use the
Encoding.UTF8
class to decode it: 例如,如果字节是编码为UTF-8的文本,则可以使用
Encoding.UTF8
类对其进行解码:
myData.Append(Encoding.UTF8.GetString(buffer));
Note that multi-byte encodings like UTF-8 may represent one character as multiple bytes, so the string length may be different from the byte array length. 请注意,像UTF-8这样的多字节编码可能会将一个字符表示为多个字节,因此字符串长度可能与字节数组长度不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.