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) { }
}

原文地址:https://www.cnblogs.com/junio/p/10765632.html

时间: 2024-08-29 03:17:54

webapi返回文件流的相关文章

vue中使用axios处理post方法导出excel表格(后端返回文件流)

使用: vue.axios 接口要求: post方法.入参为json格式.出参文件流 1.请求函数 exportExcel: function(form) { return axios({ // 用axios发送post请求 method: 'post', url: '/serviceTime/exportData', // 请求地址 data: form, // 参数 responseType: 'blob', // 表明返回服务器返回的数据类型 headers: { 'Content-Typ

接口返回文件流,如何下载

XMLHttpRequest Level 2 支持请求.responseType = 'blob' 返回的就是二进制流 var blob = result; // ie 使用 if (window.navigator.msSaveBlob) { // for ie 10 and later try { var blobObject = new Blob([blob]); window.navigator.msSaveBlob(blobObject, filename); } catch (e)

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

C#.NET WebApi返回各种类型(图片/json数据/字符串),.net图片转二进制流或byte 转载:http://www.itdos.com/Mvc/20150302/0741255.html using System.IO; /// <summary> /// WebApi返回图片 /// </summary> public HttpResponseMessage GetQrCode() { var imgPath = @"D:\ITdosCom\Images

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

1 //我的会员中心 头像上传接口 2 /*windows 调试*/ 3 @Value("${appImg.location}") 4 private String winPathPic; 5 /*linux 使用*/ 6 @Value("${img.location}") 7 private String linuxPathPic; 8 9 @PostMapping(value = "/file") 10 public String file(

前端接收后端返回的文件流导出Excel

需求:接收后端返回的文件流导出Excel 自己项目中遇到过,亲测有效 情况二使用过程中解决的问题: 1.直接接受的文件流下载格式为txt且乱码.需要通过 下面这句代码来转成Excel: let url = new Blob([xmlHttp.response], { type: 'application/vnd.ms-excel' }); 2.文件名乱码,显示数字单词组成的随机字符串.需要后端在header中返回文件名,转义获取 //文件名 link.download = decodeURICo

webapi读取上传的文件流

逻辑说明 这里未引用System.Web.Mvc. 主要使用MultipartMemoryStreamProvider对象从Request中获取文件流. var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider); var items = provider.Contents.Where(c => c.Headers.ContentDispositi

C++文件流

文件流:以文件为输入输出对象的流 #include<fstream> 一.文件操作打开一个输入或输出文件 1.打开一个输出文件 ofstream fout; fout.open("1.txt"); 2.打开一个输入文件 ifstream  fin; fin.open("2.txt"); 3.打开一个文件,既可以输入也可以输出 fstream finout: finout.open("3.txt"): 更便捷方式   ofstream

文件流:&quot;fopen&quot;,&quot;fclose&quot;,“ftell”&quot;fseek&quot;,&quot;fgets&quot;,&quot;fprintf&quot; ,“feof”,&quot;fwrite&quot;,&quot;fread&quot;

char const* filename="D:/hello.txt"; "fopen", FILE *fp=fopen(char const *name,char const mode); e.g:FILE *fp = fopen(filename,"wb"); 打开文件流,name为要打开文件的路径,如这里的filename:mode 为对文件的操作模式,通常使用:"wb"(写操作),"rb"(读操作)

C++学习47 文件的概念 文件流类与文件流对象 文件的打开与关闭

迄今为止,我们讨论的输入输出是以系统指定的标准设备(输入设备为键盘,输出设备为显示器)为对象的.在实际应用中,常以磁盘文件作为对象.即从磁盘文件读取数据,将数据输出到磁盘文件.磁盘是计算机的外部存储器,它能够长期保留信息,能读能写,可以刷新重写,方便携带,因而得到广泛使用. 文件(file)是程序设计中一个重要的概念.所谓“文件”,一般指存储在外部介质上数据的集合.一批数据是以文件的形式存放在外部介质(如磁盘.光盘和U盘)上的.操 作系统是以文件为单位对数据进行管理的,也就是说,如果想找存在外部