逻辑说明

webapi返回类型为IHttpActionResult接口,内部方法返回HttpResponseMessage

public interface IHttpActionResult
{
Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}

参照JsonResult<T>,自定义返回文件流。
主要为:设置文件响应内容流,文件内容类型,文件名。

HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(_stream);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(_fileName, Encoding.UTF8),
};

完整代码

完整FileStreamResult如下:

public class FileStreamResult : IHttpActionResult
{
readonly Stream _stream;
readonly string _mediaType;
readonly string _fileName; public FileStreamResult(Stream stream, string mediaType) : this(stream, mediaType, null) { } public FileStreamResult(Stream stream, string mediaType, string fileName)
{
_stream = stream;
_mediaType = mediaType;
_fileName = fileName;
} public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult<HttpResponseMessage>(Execute());
} private HttpResponseMessage Execute()
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
try
{
httpResponseMessage.Content = new StreamContent(_stream);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);
if (!string.IsNullOrEmpty(_fileName))
{
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(_fileName, Encoding.UTF8),
};
}
return httpResponseMessage;
}
catch
{
httpResponseMessage.Dispose();
throw;
}
}
}

使用方法:

[HttpGet]
public IHttpActionResult Logo()
{
var path = HostingEnvironment.MapPath("/files/logo.png");
var f = new FileInfo(path);
if (!f.Exists)
{
return new StatusCodeResult(HttpStatusCode.NotFound, this);
}
return new FileStreamResult(f.OpenRead(), "image/png");
} [HttpGet]
public IHttpActionResult D()
{
var path = HostingEnvironment.MapPath("/files/d.docx");
var f = new FileInfo(path);
if (!f.Exists)
{
return new StatusCodeResult(HttpStatusCode.NotFound, this);
}
return new FileStreamResult(f.OpenRead(), "application/octet-stream", "中文的jun2019.docx");
}

扩展的FileByteResult

public class FileByteResult : FileStreamResult
{
public FileByteResult(byte[] buffer, string mediaType) : base(new MemoryStream(buffer), mediaType) { } public FileByteResult(byte[] buffer, string mediaType, string fileName) : base(new MemoryStream(buffer), mediaType, fileName) { }
}

webapi返回文件流的更多相关文章

  1. Ajax异步请求返回文件流(eg:导出文件时,直接将导出数据用文件流的形式返回客户端供客户下载)

    在异步请求中要返回文件流,不能使用JQuery,因为$.ajax,$.post 不支持返回二进制文件流的类型,可以看到下图,dataType只支持xml,json,script,html这几种格式,没 ...

  2. java 后台返回文件流到浏览器

    package com.springbootblog.controller; import io.swagger.annotations.ApiImplicitParam;import io.swag ...

  3. 文件下载post请求,返回文件流转换zip,

    最近一个需求是批量下载文件,最后打包成zip包,post请求, 因为是文件流下载,所以在取后台数据的时候,要多传递一个[responseType: ‘blob’]这个参数 download() { t ...

  4. 需要加token验证的接口返回文件流下载

    没有加token之前,下载文件用的是a标签,直接下载. 现在要求是需要在header中加入token. getDownload(urls, fileName) { var url = urls; va ...

  5. c语言中的文件流

    一.打开和关闭文件 #include int main( void ) { FILE* pReadFile = fopen( "E:\\mytest.txt", "r&q ...

  6. SpringMVC(Springboot)返回文件方法

    https://blog.csdn.net/Lynn_coder/article/details/79953977 ****************************************** ...

  7. 【转载】C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte

    C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte 转载:http://www.itdos.com/Mvc/20150302/0741255.htm ...

  8. C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte

    using System.IO; /// <summary> /// WebApi返回图片 /// </summary> public HttpResponseMessage  ...

  9. springboot 头像上传 文件流保存 文件流返回浏览器查看 区分操作系统 windows 7 or linux

    //我的会员中心 头像上传接口 /*windows 调试*/ @Value("${appImg.location}") private String winPathPic; /*l ...

随机推荐

  1. Python之路【第一篇】:Python简介和入门

    python简介: 一.什么是python Python(英国发音:/ pa θ n/ 美国发音:/ pa θɑ n/),是一种面向对象.直译式的计算机程序语言. 每一门语言都有自己的哲学: pyth ...

  2. CenOS_用户级别

    1.运行级别 共有7个运行级别: 0:关机 1:单用户(不用密码也能登陆) 2:多用户无网络 3:多用户有网络 4:保留 5:图形化界面 6:重启 1.1设置运行级别语法: init <级别数字 ...

  3. 接触新的项目,构建时候报错:Failure to find io.netty:netty-tcnative:jar:${os.detected.classifier}:2.0.7.Final in

    详细信息如下: Failure to find io.netty:netty-tcnative:jar:${os.detected.classifier}:2.0.7.Final in http:// ...

  4. pgsql sql 统计整理

    字符字段转整型查询: SELECT mon_id as staTime,SUM (CAST ( index_value AS INT )) AS totalCount FROM aidata.rep_ ...

  5. 微信小程序之onLaunch与onload异步问题

    所述问题: 前端时间开发了一个微信小程序商城项目,因为这个项目我们的需求是进入小程序就通过wx.login({}) 这个api进行用户登录,获取系统后台的用户基本信息.再此之前,一直以为微信小程序中的 ...

  6. SpringMVC 参数传递和接收的几种方式

    普通传参 测试项目:SpringBoot2.0.不使用 form 表单传参,后端不需要指定 consumes . 使用 Postman 进行测试. @PathVariable 只能接收 URL 路径里 ...

  7. hibernate出现QueryException: could not resolve property 查询异常

    可能是你的属性名写错了,  因为hibernate是面向对象和属性的.

  8. Python:SQLMap源码精读—基于时间的盲注(time-based blind)

    建议阅读 Time-Based Blind SQL Injection Attacks 基于时间的盲注(time-based blind) 测试应用是否存在SQL注入漏洞时,经常发现某一潜在的漏洞难以 ...

  9. Mac下安装多版本python

    1.安装Homebrew 将命令行复制至终端,进行安装. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/H ...

  10. Python实战171203统计

    统计序列中元素出现的频次 如何统计出某一个随机数列的元素出现的次数是多少? import randomdata=[random.randint(0,7) for _ in range(15)]c=di ...