zoukankan      html  css  js  c++  java
  • Web API 自定义文件内容的定制类

        public class FileContent : HttpContent
        {
            private readonly Stream _stream;
    
            public FileContent(string path, string mediaType = "application/octet-stream")
            {
                _stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType);
            }
    
    
            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
            {
                return _stream.CopyToAsync(stream);
            }
    
            protected override bool TryComputeLength(out long length)
            {
                if (_stream.CanSeek)
                {
                    length = _stream.Length;
                    return true;
                }
    
                length = 0;
                return false;
            }
    
            protected override void Dispose(bool disposing)
            {
                _stream.Dispose();
            }
        }

    调用

                string path = @"H:各类知识练习MyWebApiWebApiImg1.jpg";
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new FileContent(path) //默认提示下载
                    //Content = new FileContent(path,"image/jpg") //直接显示图片
                };
                return response;
  • 相关阅读:
    [LeetCode] 101. 对称二叉树
    [LeetCode] 394. 字符串解码!!!!
    USACO Ordered Fractions
    USACO The Castle
    遇到的Mysql的一个坑
    USACO-palsquare 遇到的一个坑
    大整数相乘
    vs2012扩展
    JS实现文字倒计数
    jqAutoComplete 和 knockout
  • 原文地址:https://www.cnblogs.com/refuge/p/10610737.html
Copyright © 2011-2022 走看看