我有一个闪存记录器,它记录用户输入并给我一个 JavaScript 字节数组文件
现在我想将该字节数组上传到服务器(MVC3),我想知道如何做到这一点?
最佳答案
您可以使用 AJAX 请求将字节数组作为原始数据发送到服务器。我们可以实现一个自定义模型绑定(bind)器,它将读取原始请求正文并将其映射到 byte[]
:
public class ByteArrayModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var buffer = new byte[request.InputStream.Length];
request.InputStream.Read(buffer, 0, buffer.Length);
return buffer;
}
}
然后我们可以有一个 Controller 操作来接收此请求:
[HttpPost]
public ActionResult Upload([ModelBinder(typeof(ByteArrayModelBinder))] byte[] buffer)
{
// TODO: do something with the uploaded data
return Json(true);
}
最后在客户端发送AJAX请求:
// create sample data from the A,B,C bytes:
var data = String.fromCharCode(65, 66, 67);
$.ajax({
url: '@Url.Action("upload")',
type: 'POST',
contentType: 'application/octet-stream',
processData: false,
data: data,
success: function (result) {
alert(result);
}
});
关于c# - 我如何在 Javascript 中处理文件 ByteArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868371/