逻辑说明

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. android---动画入门(一)

    android 动画分为两类,View Animation(视图动画)和property Animation(属性动画),View Animation(视图动画)包含了Tween Animation和 ...

  2. SQL Server2008进程堵塞处理方法

    进程堵塞处理方法: select * from sys.sysprocesses where blocked <>0 and DB_NAME(dbid)='GSHCPDB'   ##查询堵 ...

  3. Win7系统修改hosts无法保存怎么办?

    背景 有的时候我们需要修改hosts文件,但是在某些情况下竟提示保存不了.之前有一次IntelliJ IDEA提示我快到期了,于是我到网上找到了一个激活方法,但需要将一个地址放到hosts文件中去,此 ...

  4. kerberos环境storm配置:Running Apache Storm Securely

    Running Apache Storm Securely Apache Storm offers a range of configuration options when trying to se ...

  5. 阿里巴巴excel工具easyexcel 助你快速简单避免OOM

    Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有 ...

  6. Java数据结构和算法 - 简单排序

    Q: 冒泡排序? A: 1) 比较相邻的元素.如果第一个比第二个大,就交换它们两个; 2) 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对.在这一点,最后的元素应该会是最大的数; 3) 针 ...

  7. Hadoop系列009-NameNode工作机制

    本人微信公众号,欢迎扫码关注! NameNode工作机制 1 NameNode & SecondaryNameNode工作机制 1.1 第一阶段:namenode启动 1)第一次启动namen ...

  8. 限定项目的 Node.js 版本

    限定项目运行所需的 Node.js 版本可保证项目在一个稳定可预期的环境中运行,减少不必要的故障.甚至有些依赖库只能工作于某些版本下.同时,不加以限制的话,在多人合作的项目中恐怕会引起环境不一致带来的 ...

  9. python3-随机生成10位包含数字和字母的密码

    方法一: 知识点:random.sample(sequence, k) 从指定序列中随机获取指定长度的片断 import random,string num=string.ascii_letters+ ...

  10. Linux系统上安装MySQL(rpm)

    1.准备工作 从MySQL官网上分别下载mysql服务器端于客户端包. 如: MySQL-server-5.5.15-1.linux2.6.x86_64.rpm和MySQL-client-5.5.15 ...