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 ...
随机推荐
- OGG-02803 Encountered a Data Guard role transition
告警提示其实已经很明显了OGG-02803 Encountered a Data Guard role transition. Alter Extract to SCN 15,756,246 and ...
- July 10th, 2018. Tuesday, Week 28th
Winning isn't everything, but wanting it is. 胜利并不能代表一切,但求胜心可以. From Arnold Palmer. Compared to this ...
- GetForegroundWindow获取的是托管进程ApplicationFrameHost,而不是真正的进程,比如XD软件
问题描述 最近做一个实时检测系统当前激活进程的软件,Photoshop.PPT.Word都没有问题,但是无法检测到XD软件的进程,返回的仅仅是ApplicationFrameHost进程,经过研究发现 ...
- 题目:python 打印出如下图案(菱形):
# 题目:打印出如下图案(菱形): # # * # *** # ***** # ******* # ***** # *** # * nu = 1 # 开始值 k = 2 # 变量值 while nu ...
- 主机与虚拟机都可以上网,但是互相ping不通
问题:主机与虚拟机都可以上网,但是互相ping不通 可能:相关入站规则没有启用 解决:第4步双击后,打勾设置“已启用”
- JVM回收器与调优
定义: 使用编程语言将GC算法实现出来,产生的程序就是垃圾搜集器了 JVM给了三种选择:串行收集器.并行收集器.并发收集器 串行搜集器(serial collector):它只有一条GC线程,且就像前 ...
- python默认编码设置
打开python 的gui,输入 1 2 import sys sys.getdefaultencoding() 查询系统当前默认编码 默认情况下显示编码方式为ASCII 在python安装目录下 ...
- 微信小程序开发07-列表页面怎么做
接上文:微信小程序开发06-一个业务页面的完成 github地址:https://github.com/yexiaochai/wxdemo 我们首页功能基本完成,我对比了下实际工作中的需求,完成度有7 ...
- Python使用Ctypes与C/C++ DLL文件通信过程介绍及实例分析
项目中可能会经常用到第三方库,主要是出于程序效率考虑和节约开发时间避免重复造轮子.无论第三方库开源与否,编程语言是否与当前项目一致,我们最终的目的是在当前编程环境中调用库中的方法并得到结果或者借助库中 ...
- [JavaScript] requireJS基本使用
requireJS 是一个 AMD 规范的模块加载器主要解决的js开发的4个问题1. 异步加载,防止阻塞页面渲染2. 解决js文件之间的依赖关系和保证js的加载顺序3. 按需加载 来实现一个 requ ...