ASP.NET MVC4中绑定图像的字节数组

时间:2015-04-23 14:49:50

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor

我在MVC4视图中绑定来自字节数组的图像,从WEB API返回字节数组,我需要将其绑定到视图。

以下是代码

string str="JVBERi0xLjUNJeLjz9MNCjQgMCBvYmoNPDwvRSA0NDc1L0ggWyA3NjMgMTI1IF0vTCA1MTczL0xpbmVhcml6ZWQgMS9OIDEvTyA2L1QgNDcwMj4+DWVuZG9iag0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA0xNCAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbNCAxMV0vSW5mbyAzIDAgUi9MZW5ndGggNTQvUHJldiA0NzAzL1Jvb3QgNSAwIFIvU2l6ZSAxNS9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiZBBgYGJg2gAkGHeAiLlAgiEHSPAUMTAxfhADcRkYmf4zffrPxCCQAuS+C2cAALmiCM4KZW5kc3RyZWFtDWVuZG9iag1zdGFydHhyZWYNIDANJSVFT0YNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ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akKmi4WBkZGJoamBgaGxkYmRqYRhkYqAORpr5vfgoBFQFF+SmlyalFChoBLm4hRfl5CkDaL7VERyHMTM/YwMjEKCZP084OAIrZKrEKZW5kc3RyZWFtDWVuZG9iag0xMyAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbMCA0XS9JbmZvIDMgMCBSL0xlbmd0aCAyNC9Sb290IDUgMCBSL1NpemUgNC9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiAAImRsFqIPG+jYEJyGMEABJTAg0KZW5kc3RyZWFtDWVuZG9iag10cmFpbGVyDTw8L1NpemUgNA0vSUQgWyhuXDM2NFxmXDIzNlwzMjVcMjYyfVwyNjRcMjcwXDM1MCpcMTc3XDAzN1wzNjdcMDA3XDMxNikgKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KV0+Pg1zdGFydHhyZWYNMTgyDSUlRU9GDQ==";

                   Byte[] image = GetBytes(str);

                    {
                        Model.ImageData = image;
                    }

 static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

在视图中将其绑定为

 <img src="data:image;base64,@System.Convert.ToBase64String(Model.ImageData)" />

图像未渲染,仅在页面中显示图像图标。

哪里出错了。请建议。

1 个答案:

答案 0 :(得分:1)

你的str看起来已经是base64了,所以你不需要跳到二进制和后退。你可以把它放在它应该的视图中。

从base64解码该字符串后发现它不是图像,它是一个pdf文件。 所以你的api(3d派对,我猜)不是为你服务的。

最后要成功使用这样的图像,您可能需要指定mime类型,如<img src="data:image/png;base64,some text representation of binary data" />

http://en.wikipedia.org/wiki/Data_URI_scheme