ASP的.NET Web API下载图像为二进制 [英] ASP .Net Web API downloading images as binary

查看:128
本文介绍了ASP的.NET Web API下载图像为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试使用的Web API进行REST调用,但我想回应是存储在数据库中,而不是一个JSON的base64连接codeD字符串实际的二进制图像。任何人都得到一些指点一下吗?

更新 -
这是我最后落实

 的Htt presponseMessage结果=新的Htt presponseMessage(的HTTPStatus code.OK);
 result.Content =新StreamContent(新的MemoryStream(profile.Avatar));
 result.Content.Headers.ContentType =新MediaTypeHeaderValue(应用程序/八位字节流);
 result.Content.Headers.ContentDisposition =新ContentDispositionHeaderValue(附件);
 result.Content.Headers.ContentDisposition.FileName =avatar.png;
 返回结果;


解决方案

您可以设置响应内容到StreamContent对象:

  VAR FILESTREAM =新的FileStream(路径,FileMode.Open);        VAR RESP =新的Htt presponseMessage()
        {
            内容=新StreamContent(FILESTREAM)
        };        //查找MIME类型
        串mime类型= _extensions [Path.GetExtension(路径)];
        resp.Content.Headers.ContentType =新MediaTypeHeaderValue(mime类型);

I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?

Update- This is what I ended up implementing:

 HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
 result.Content = new StreamContent(new MemoryStream(profile.Avatar));
 result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
 result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
 result.Content.Headers.ContentDisposition.FileName = "avatar.png";
 return result;

解决方案

You can set the response content to a StreamContent object:

        var fileStream = new FileStream(path, FileMode.Open);

        var resp = new HttpResponseMessage()
        {
            Content = new StreamContent(fileStream)
        };

        // Find the MIME type
        string mimeType = _extensions[Path.GetExtension(path)];
        resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);

这篇关于ASP的.NET Web API下载图像为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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