取消

webApi返回文件流

webApi返回文件流


定义返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
[DataContract]
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(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;
        }
    }
}

使用

1
2
3
4
5
6
7
public async Task<FileStreamResult> GetFile(string path)
{
    var f = new FileInfo(path);
    //return new FileStreamResult(f.OpenRead(), "application/octet-stream", "result.docx");
    var mediaType = MimeMapping.GetMimeMapping(path);
    return new FileStreamResult(f.OpenRead(), mediaType, "result"+Path.GetExtension(path));
}

本文会经常更新,请阅读原文: https://dashenxian.github.io/post/webApi%E8%BF%94%E5%9B%9E%E6%96%87%E4%BB%B6%E6%B5%81 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

知识共享许可协议

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com)

登录 GitHub 账号进行评论