【问题标题】:How to "download" from data: URIs?如何从数据中“下载”:URI?
【发布时间】:2013-02-08 18:59:34
【问题描述】:

我有一个 data: URI,我需要使用普通的 .Net WebClient/WebRequest “下载”(读取:作为流或字节数组加载)。我该怎么做?

我需要这个,因为我想显示一个从 SVG 生成的 XAML 文件,其中包括一些使用 data: URI 的图像。我不想总是解析 XAML,将图像保存到磁盘,然后将 XAML 更改为指向文件。我相信 WPF 在内部使用 WebRequest 来获取这些图像。

【问题讨论】:

    标签: c# .net data-uri


    【解决方案1】:

    您可以使用WebRequest.RegisterPrefix() 来执行此操作。您将需要实现IWebRequestCreate,它返回一个自定义WebRequest,它返回一个自定义WebResponse,最终可以用于从URI 中获取数据。它可能看起来像这样:

    public class DataWebRequestFactory : IWebRequestCreate
    {
        class DataWebRequest : WebRequest
        {
            private readonly Uri m_uri;
    
            public DataWebRequest(Uri uri)
            {
                m_uri = uri;
            }
    
            public override WebResponse GetResponse()
            {
                return new DataWebResponse(m_uri);
            }
        }
    
        class DataWebResponse : WebResponse
        {
            private readonly string m_contentType;
            private readonly byte[] m_data;
    
            public DataWebResponse(Uri uri)
            {
                string uriString = uri.AbsoluteUri;
    
                int commaIndex = uriString.IndexOf(',');
                var headers = uriString.Substring(0, commaIndex).Split(';');
                m_contentType = headers[0];
                string dataString = uriString.Substring(commaIndex + 1);
                m_data = Convert.FromBase64String(dataString);
            }
    
            public override string ContentType
            {
                get { return m_contentType; }
                set
                {
                    throw new NotSupportedException();
                }
            }
    
            public override long ContentLength
            {
                get { return m_data.Length; }
                set
                {
                    throw new NotSupportedException();
                }
            }
    
            public override Stream GetResponseStream()
            {
                return new MemoryStream(m_data);
            }
        }
    
        public WebRequest Create(Uri uri)
        {
            return new DataWebRequest(uri);
        }
    }
    

    这仅支持base64编码,但可以轻松添加对URI编码的支持。

    然后你像这样注册它:

    WebRequest.RegisterPrefix("data", new DataWebRequestFactory());
    

    是的,这确实适用于检索数据:XAML 文件中的图像。

    【讨论】:

    • 这个答案拯救了我的一天。实现 WebRequest 类时还要覆盖 Icredentials。
    猜你喜欢
    • 2018-02-01
    • 2015-07-27
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多