示例#1
0
        private async Task ImportFirstImageAsync(IContentBase postNode, IContentType postType, BlogMLPost post)
        {
            var imageMimeTypes = new List <string> {
                "image/jpeg", "image/gif", "image/png"
            };

            var attachment = post.Attachments.FirstOrDefault(p => imageMimeTypes.Contains(p.MimeType));

            if (attachment == null)
            {
                return;
            }

            var imageSaved = false;

            if (!attachment.Content.IsNullOrWhiteSpace())
            {
                //the image is base64
                var bytes = Convert.FromBase64String(attachment.Content);
                using (var stream = new MemoryStream(bytes))
                {
                    postNode.SetInvariantOrDefaultCultureValue(_contentTypeBaseServiceProvider, "postImage", attachment.Url.OriginalString, stream, postType, _localizationService);
                    imageSaved = true;
                }
            }
            else if (attachment.ExternalUri != null && attachment.ExternalUri.IsAbsoluteUri)
            {
                try
                {
                    using (var client = new HttpClient())
                    {
                        using (var stream = await client.GetStreamAsync(attachment.ExternalUri))
                        {
                            postNode.SetInvariantOrDefaultCultureValue(_contentTypeBaseServiceProvider, "postImage", Path.GetFileName(attachment.ExternalUri.AbsolutePath), stream, postType, _localizationService);
                            imageSaved = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    _logger.Error <BlogMlImporter>(exception, "Exception retrieving {AttachmentUrl}; post {PostId}", attachment.Url, post.Id);
                }
            }

            if (imageSaved)
            {
                //this is a work around for the SetValue method to save a file, since it doesn't currently take into account the image cropper
                //which we are using so we need to fix that.

                var propType     = postNode.Properties["postImage"].PropertyType;
                var cropperValue = CreateImageCropperValue(propType, postNode.GetValue("postImage"), _dataTypeService);
                postNode.SetInvariantOrDefaultCultureValue("postImage", cropperValue, postType, _localizationService);
            }
        }