Nav
Nav

Reputation: 71

How to check file extension before displaying in view

I have a project where I need to display images and videos. I am saving both image and videos URL inside a table called Images and while retrieving I am using image handler for images to resize the image on the server level. Right now my code to display images and video is just this line

<td>
                                <img src="~/[email protected](modelItem => item.url)" />
                            </td>

I need something like below to identify the file extension before displaying. if the extension is png or jpeg go to this line else this line. How can I do like below or any other better option?

                        @foreach (var item in Model)
                        {
                            <tr>
                                if (extension == .png || extension == .jpeg )
                                {
                                <td>
                                    <img src="~/[email protected](modelItem => item.url)" />
                                </td>
                                }
                                else
                                {
                                <td>
                                    <video width="240" height="240" autoplay>
                                        <source src="@Html.DisplayFor(modelItem => item.url)" type="video/mp4">
                                    </video>
                                </td>
                                }
                                <td>
                                    @Html.DisplayFor(modelItem => item.details)
                                </td>
                            </tr>
                        }

Upvotes: 0

Views: 1662

Answers (2)

Jason Brown
Jason Brown

Reputation: 93

If the model only contains the url/path to the file you could split the string with the delimiter as "." and get the last element in the resulting array of strings.
Eg:

@foreach(var item in Model)
{
    var extn = item.url.Split(".").Last();
    if (extn == ".png" || extn == ".jpeg" )
    {
        @*Do image display*@
    }
    else
    {
       @*Do video display*@
    }
}

Not sure if this is optimal, but i cant think of another way to do it.

Upvotes: 2

NetMage
NetMage

Reputation: 26917

You can use HttpClient to check for the Content-Type of the URL and then decide how to handle it:

public static class URLExt {
    public static string GetMimeType(this string url) {
        using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })) {
            var r = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false).GetAwaiter().GetResult();
            return r.IsSuccessStatusCode ? r.Content.Headers.ContentType.MediaType : null;
        }
    }
}

Upvotes: 0

Related Questions