Skip to content

Commit 1df8d9f

Browse files
committed
Added file-type detection
1 parent 22da298 commit 1df8d9f

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/LinkDotNet.Blog.Web/Features/Components/PreviewImage.razor

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
@using Microsoft.AspNetCore.StaticFiles
12
@if (string.IsNullOrEmpty(PreviewImageUrlFallback))
23
{
34
<img src="@PreviewImageUrl" alt="Preview image blogpost" loading="@LazyLoadTag"/>
45
}
56
else
67
{
78
<picture>
8-
<source srcset="@PreviewImageUrl" />
9+
<source srcset="@PreviewImageUrl" type="@GetMimeType()"/>
910
<img src="@PreviewImageUrlFallback" alt="Preview image blogpost" loading="@LazyLoadTag"/>
1011
</picture>
1112
}
@@ -21,4 +22,20 @@ else
2122
public bool LazyLoadImage { get; set; }
2223

2324
private string LazyLoadTag => LazyLoadImage ? "lazy" : "eager";
25+
26+
private static readonly FileExtensionContentTypeProvider Provider = new();
27+
28+
static PreviewImage()
29+
{
30+
if (!Provider.Mappings.Keys.Contains(".avif"))
31+
{
32+
Provider.Mappings.Add(".avif", "image/avif");
33+
}
34+
}
35+
36+
private string GetMimeType()
37+
{
38+
Provider.TryGetContentType(PreviewImageUrl, out var contentType);
39+
return contentType;
40+
}
2441
}

tests/LinkDotNet.Blog.UnitTests/Web/Features/Components/PreviewImageTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,20 @@ public void ShouldSetLazyLoadBehaviorNoFallback(bool lazyLoad, string expectedLa
6868

6969
image.Attributes.FirstOrDefault(a => a.Name == "loading").Value.Should().Be(expectedLazy);
7070
}
71+
72+
[Theory]
73+
[InlineData("http://localhost/image.png", "image/png")]
74+
[InlineData("http://localhost/image.webp", "image/webp")]
75+
[InlineData("http://localhost/image.avif", "image/avif")]
76+
public void ShouldDetectFileTypes(string fileName, string mimeType)
77+
{
78+
var cut = RenderComponent<PreviewImage>(ps => ps
79+
.Add(p => p.PreviewImageUrl, fileName)
80+
.Add(p => p.PreviewImageUrlFallback, "not empty"));
81+
82+
var picture = cut.Find("picture");
83+
84+
var source = picture.Children[0] as IHtmlSourceElement;
85+
source.Type.Should().Be(mimeType);
86+
}
7187
}

0 commit comments

Comments
 (0)