上载/下载字节数组与AngularJS和ASP.NET Web API [英] Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API

查看:248
本文介绍了上载/下载字节数组与AngularJS和ASP.NET Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了好几天的研究​​和对上传/下载字节的[]的解决方案的工作。我靠近,但似乎是在我的AngularJS code座剩下的一个问题。

I have spent several days researching and working on a solution for uploading/downloading byte[]’s. I am close, but have one remaining issue that appears to be in my AngularJS code block.

有是SO过类似的问题,但它没有响应。请参见的Web API接受和后字节数组

There is a similar question on SO, but it has no responses. See Web API accept and post byte array

下面是一些背景信息设置上下文之前,我说出了我的问题。

Here is some background information to set the context before I state my problem.


  1. 我试图创建一个通用的客户端/服务器接口上传和下载的byte []的,这是作为一个专有服务器数据库的一部分。

  2. 我用的打字稿,AngularJS,JavaScript和CSS引导客户机上创建一个单页的应用程序(SPA)。

  3. 我使用的ASP.NET Web API / C服务器上的#。

该SPA正在开发以取代已在Silverlight开发的,因此被限制在现有的系统需求的现有产品。水疗中心还需要针对各种设备(移动到桌面)和主要操作系统。

The SPA is being developed to replace an existing product that was developed in Silverlight so it is constrained to existing system requirements. The SPA also needs to target a broad range of devices (mobile to desktop) and major OSs.

随着几个在线资源(见下表)的帮助下,我已经得到了我的大部分code工作的。我使用的是异步的多媒体格式的字节[]从下面的字节腐链接的。

With the help of several online resources (listed below), I have gotten most of my code working. I am using an asynchronous multimedia formatter for byte[]’s from the Byte Rot link below.

<一个href=\"http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html\">http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html

<一个href=\"http://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api\">Returning从的ASP.NET Web API 控制器二进制文件


  1. 我使用转换为Uint8Array作为客户对我的测试案例jpeg文件。

  2. 系统的实际字节数组将包含压缩成predefined数据包混合内容。不过,我需要能够处理任何有效的字节数组这样的图像是一个有效的测试用例。

  3. 的数据被使用客户端和服务器code如下所示,并且字节腐格式化(未示出,但可在其网站上)。正确地发送到服务器

  4. 我已经验证了JPEG是正确接收的服务器作为一个byte [用字符串参数元数据]上。

  5. 我已经使用的Fiddler来验证正确的响应发送回客户端。

    • 的大小是正确

    • 的图像是提琴手查看。

我的问题是,如下所示的角端code服务器的响应是不正确的。


  • 由不正确的,我的意思是在错误的大小(约10K〜对27.5K),这是不会确认为UintArray构造一个有效的值。 Visual Studio中显示JFIF当我将光标放在客户端$ C $下面c所示返回回应,但内容没有其他明显的标志。

  • By incorrect, I mean the wrong size (~10K versus ~27.5K) and it is not recognized as a valid value for the UintArray constructor. Visual Studio shows JFIF when I place the cursor over the returned "response" shown in the client code below, but there is no other visible indicator of the content.

/ ****************** 服务器code ************* ******* /
新增失踪项目code后[FromBody]字节[]

/****************** Server Code ********************/ Added missing item to code after [FromBody]byte[]

public class ItemUploadController : ApiController{ 
[AcceptVerbs("Post")]
    public HttpResponseMessage Upload(string var1, string var2, [FromBody]byte[] item){
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new MemoryStream(item);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }
}

/ ************* 示例客户端code **************** /

/************* Example Client Code ****************/

这是我从code忽略的唯一的事情是实际的可变参数。

The only thing that I have omitted from the code are the actual variable parameters.

$http({
url: 'api/ItemUpload/Upload',
    method: 'POST',
    headers: { 'Content-Type': 'application/octet-stream' },// Added per Byte Rot blog...
    params: {
        // Other params here, including string metadata about uploads
        var1: var1,
        var2: var2
    },
data: new Uint8Array(item),
// arrybuffer must be lowecase. Once changed, it fixed my problem.
responseType: 'arraybuffer',// Added per http://www.html5rocks.com/en/tutorials/file/xhr2/
transformRequest: [],
})
.success((response, status) => {
    if (status === 200) {
        // The response variable length is about 10K, whereas the correct Fiddler size is ~27.5K.
        // The error that I receive here is that the constructor argument in invalid.
        // My guess is that I am doing something incorrectly with the AngularJS code, but I
        // have implemented everything that I have read about. Any thoughts???
        var unsigned8Int = new Uint8Array(response);
        // For the test case, I want to convert the byte array back to a base64 encoded string
        // before verifying with the original source that was used to generate the byte[] upload.
        var b64Encoded = btoa(String.fromCharCode.apply(null, unsigned8Int));
        callback(b64Encoded);
    }
})
.error((data, status) => {
    console.log('[ERROR] Status Code:' + status);
});

/ ********* ***************** /

任何帮助或建议将不胜AP preciated。

Any help or suggestions would be greatly appreciated.

谢谢...

编辑,包括更多的诊断数据

首先,我用angular.isArray函数来确定响应值是不是一个数组,我认为是应该的。

First, I used the angular.isArray function to determine that the response value is NOT an array, which I think it should be.

二,我用下面的code询问的响应,这似乎是一种无形的字符串。主人公似乎并不对应于图像的字节数组code任何有效的序列。

Second, I used the following code to interrogate the response, which appears to be an invisible string. The leading characters do not seem to correspond to any valid sequence in the image byte array code.

var buffer = new ArrayBuffer(response.length);
var data = new Uint8Array(buffer);
var len = data.length, i;
for (i = 0; i < len; i++) {
    data[i] = response[i].charCodeAt(0);
}

实验结果

我从0创建字节数组值运行的实验。所述AngularJS客户正确地接收到的第一128个字节(即,0,1,...,126,127),但其余的值在Internet Explorer中11人65535和65533中铬和Firefox。菲德勒显示,256值是通过网络发送,但只有217在AngularJS客户code接收到的字符。如果我只用0-127作为服务器值,一切似乎工作。我不知道是什么原因,但客户的反应似乎更符合符号字节,这我不认为是可能的。

I ran an experiment by creating byte array values from 0 - 255 on the server, which I downloaded. The AngularJS client received the first 128 bytes correctly (i.e., 0,1,...,126,127), but the remaining values were 65535 in Internet Explorer 11, and 65533 in Chrome and Firefox. Fiddler shows that 256 values were sent over the network, but there are only 217 characters received in the AngularJS client code. If I only use 0-127 as the server values, everything seems to work. I have no idea what can cause this, but the client response seems more in line with signed bytes, which I do not think is possible.

从服务器提琴手十六进制数据显示,256字节的取值范围为00,01价值观,...,EF,FF,这是正确的。正如我前面提到的,我可以返回一个图像,并查看它在适当的提琴手,所以Web API服务器接口同时适用于POST和GET。

Fiddler Hex data from the server shows 256 bytes with the values ranging from 00,01,...,EF,FF, which is correct. As I mentioned earlier, I can return an image and view it properly in Fiddler, so the Web API server interface works for both POST and GET.

我试图香草XMLHtt prequest看看我能得到工作AngularJS环境之外。

I am trying vanilla XMLHttpRequest to see I can get that working outside of the AngularJS environment.

XMLHtt prequest测试更新

我已经能够确认香草XMLHtt prequest与服务器适用于GET和能够返回正确的字节codeS和测试图像。

I have been able to confirm that vanilla XMLHttpRequest works with the server for the GET and is able to return the correct byte codes and the test image.

好消息是,我可以入侵周围AngularJS让我的系统工作,但坏消息是,我不喜欢这样做。我想preFER留在角为我所有的客户端服务器通信。

The good news is that I can hack around AngularJS to get my system working, but the bad news is that I do not like doing this. I would prefer to stay with Angular for all my client-side server communication.

我要开辟堆栈溢出一个单独的问题,只有与我有AngularJS的GET字节[]的问题涉及。如果我能得到解决,我会更新的解决方案这个问题历史的目的去帮助别人。

I am going to open up a separate issue on Stack Overflow that only deals with the GET byte[] issues that I am have with AngularJS. If I can get a resolution, I will update this issue with the solution for historical purposes to help others.

更新

埃里克Eslinger在谷歌网上论坛给我发了一个小code段着重指出的responseType应该是arraybuffer,全部小写。我更新了code座以上,以显示小写值并添加注释。

Eric Eslinger on Google Groups sent me a small code segment highlighting that responseType should be "arraybuffer", all lower case. I updated the code block above to show the lowercase value and added a note.

谢谢...

推荐答案

我终于收到了从埃里克Eslinger在谷歌集团的回应。他指出,他使用

I finally received a response from Eric Eslinger on Google Group. He pointed out that he uses

$http.get('http://example.com/bindata.jpg', {responseType: 'arraybuffer'}).

他提到,驼峰可能是显著,这是。改变一个字符,整个流程现在正在工作。

He mentioned that the camelcase was probably significant, which it is. Changed one character and the entire flow is working now.

一切归功于埃里克Eslinger。

All credit goes to Eric Eslinger.

这篇关于上载/下载字节数组与AngularJS和ASP.NET Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆