Ejemplo n.º 1
0
        public async Task <FileModel> DownloadUrlAsync(Uri url, string userAgent = null, CancellationToken ct = default(CancellationToken))
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (string.IsNullOrEmpty(userAgent))
            {
                userAgent = null;
            }
            var fm = new FileModel {
                ObjectName = url.ToObjectName(),
            };

            using (var httpClient = new HttpClient()) {
                var ua       = userAgent ?? _config.GetValue("DOWNLOAD_USER_AGENT");
                var response = await httpClient.SendAsync(HttpMethod.Get, url, ua, _sizeLimit, ct : ct);

                fm.Content     = response.Content;
                fm.ContentType = response.ContentType;
                if (string.IsNullOrEmpty(fm.ContentType) && fm.Content != null && fm.Content.Length > 1)
                {
                    var contentType = MimeTypes.GetFileType(() => fm.Content, null, fm.Content);
                    if (contentType != null && !string.IsNullOrWhiteSpace(contentType.Mime))
                    {
                        fm.ContentType = contentType.Mime;
                    }
                }
            }

            return(fm);
        }
Ejemplo n.º 2
0
        public static string GetMimeFromStream(Stream stream)
        {
            if (null == stream)
            {
                throw new ArgumentNullException("stream");
            }

            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position  = 0;
            }

            try
            {
                var bufferSize = stream.Length > MaxHeaderLength ? MaxHeaderLength : stream.Length;
                var buffer     = new byte[bufferSize];
                stream.Read(buffer, 0, MaxHeaderLength);
                var fileType = MimeTypes.GetFileType(buffer);
                return(fileType.Mime);
            }
            catch (Exception)
            {
                return("unknown/unknown");
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }