webapi返回文件流
逻辑说明
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返回文件流的更多相关文章
- Ajax异步请求返回文件流(eg:导出文件时,直接将导出数据用文件流的形式返回客户端供客户下载)
在异步请求中要返回文件流,不能使用JQuery,因为$.ajax,$.post 不支持返回二进制文件流的类型,可以看到下图,dataType只支持xml,json,script,html这几种格式,没 ...
- java 后台返回文件流到浏览器
package com.springbootblog.controller; import io.swagger.annotations.ApiImplicitParam;import io.swag ...
- 文件下载post请求,返回文件流转换zip,
最近一个需求是批量下载文件,最后打包成zip包,post请求, 因为是文件流下载,所以在取后台数据的时候,要多传递一个[responseType: ‘blob’]这个参数 download() { t ...
- 需要加token验证的接口返回文件流下载
没有加token之前,下载文件用的是a标签,直接下载. 现在要求是需要在header中加入token. getDownload(urls, fileName) { var url = urls; va ...
- c语言中的文件流
一.打开和关闭文件 #include int main( void ) { FILE* pReadFile = fopen( "E:\\mytest.txt", "r&q ...
- SpringMVC(Springboot)返回文件方法
https://blog.csdn.net/Lynn_coder/article/details/79953977 ****************************************** ...
- 【转载】C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte
C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte 转载:http://www.itdos.com/Mvc/20150302/0741255.htm ...
- C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte
using System.IO; /// <summary> /// WebApi返回图片 /// </summary> public HttpResponseMessage ...
- springboot 头像上传 文件流保存 文件流返回浏览器查看 区分操作系统 windows 7 or linux
//我的会员中心 头像上传接口 /*windows 调试*/ @Value("${appImg.location}") private String winPathPic; /*l ...
随机推荐
- psql 关于主键自增的问题
在psql中往往我们需要设置一个自增的主键id字段,psql中不像SQL Server那样点选 打钩傻瓜式就能设置好的,是需要创建序列的:CREATE SEQUENCE,关键字SEQUENCE. 我们 ...
- 解决 win10飞行模式 无限自动开关 无法关闭
驱动问题,名为“Insyde Airplane Mode HID Mini-Driver”的驱动,这个驱动是专门用来快捷管理飞行模式的. 卸载完成后重启,无限开关飞行模式问题得到解决!
- Windows Server 2016-Powershell新建用户补充
前边我们介绍到Windows Server 2016-图形化新建域用户(一) 及 Windows Server 2016-批量新建域用户(二) ,里边提到了批量通过new-aduser常见帐号,这里简 ...
- eShopOnContainers 知多少[2]:Run起来
环境准备 Win10(开启Hyper-V) .NET Core SDK Docker for Windows VS2017 or VS Code Git SQL Server Management S ...
- js随机背景颜色
// 要求: 随机生成颜色RGB 核心点 :(0,0,0) rgb 每一组的数字取值范围是 0~255 // 需要随机生成 0~255 之间的整数 function getRandom(min, ma ...
- SQL中关于不能显示count为0的行的问题
今天在写自己一个博客项目时遇到了一个数据库问题,因为对于数据库自己所知道的还是很浅显的,对一些查询语句不怎么熟悉. 我目前有一个文章表和评论表,评论表里面有个post_id对应文章表里面的id,想查询 ...
- ionic4 混合移动开发 (前世今生)
ionic 从2016年初识,经历了 ionic2 ionic3.至今 ionic4,终于在2018年7月份发布了测试版. ionic Framework 可以说得上是最接近原生app的ui组件,漂亮 ...
- .NET Core微服务之基于Ocelot+Butterfly实现分布式追踪
Tip: 此篇已加入.NET Core微服务基础系列文章索引 一.什么是Tracing? 微服务的特点决定了功能模块的部署是分布式的,以往在单应用环境下,所有的业务都在同一个服务器上,如果服务器出现错 ...
- 多机同步管理hexo博客
转载自:https://www.zhihu.com/question/21193762/answer/79109280 一.关于搭建的流程 创建仓库,<your github username& ...
- GOF23种设计模式概括
GOF23种设计模式分为三种: 创建型模式[工厂方法模式]结构型模式[(类)适配器模式]行为型模式[ 解释器模式,模板方法模式] 创建型模式Creational Patterns抽象工厂模式abs ...