通过URL检测媒体(图片、视频)类型

问题描述 投票:0回答:3

根据 URL,我需要显示

<img>
<video>
。有没有办法根据 URL 检测媒体类型?或者也许有一些通用的 html 标签允许查看图像和视频?并且 URL 末尾没有特定的文件扩展名。

javascript html angular
3个回答
3
投票

一个简单的解决方案,您可以从 URL 中提取扩展名并搜索

Map()
以将元素类型与扩展名匹配:

const types = new Map([["jpg", "img"], ["gif", "img"], ["mp4", "video"], ["3gp", "video"]])

const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]

const element = document.createElement(types.get(extension))
element.src = url

原答案

创建两个映射到 img 和视频文件的文件扩展名列表。将它们存储为两个数组。

当您遇到 URL - 用户输入、来自 REST 的 JSON 等 - 找到 URL 中的扩展名并查看它属于哪个列表。

然后创建您的元素并将 URL 注入其源中,例如:

const images = ["jpg", "gif", "png"]
const videos = ["mp4", "3gp", "ogg"]

const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]

if (images.includes(extension)) {
  let img = document.createElement('img');
  img.src = url;
} else if (videos.includes(extension)) {
  let video = document.createElement('video');
  video.src = url;
}

这不是一个特别强大的解决方案:也许您的路径中有点,但至少使用

URL()
将提取可能包含参数的 URL 的文件部分。

注意

createElement
将任何 DOM 节点作为父节点,它不一定是
document


0
投票

如果 URL 指向远程服务器上的本机文件,例如 JPG、PNG 或其他图像(视频相同),那么您可以在最后一个周期上进行拆分并获取扩展名。

一旦知道扩展名,您就可以执行逻辑来确定它是图像扩展名还是视频扩展名。

否则,您只需启动文件的编程下载,然后执行相同的检查。


0
投票
const isVideoUrl = (url) => {   
    const indexOfTheAssetType = url.split(".").length - 1; // because the extension will always be at the end   
    const assetType = url.split(".")[indexOfTheAssetType].toUpperCase();   
    const isTheAssetVideoType = [
        "WEBM",
        "MPG",
        "MPEG",
        "MPE",
        "MP4",
        "M4P",
        "M4V",
        "AVI",
        "WMV",
        "MOV"].includes(assetType);   
    return isTheAssetVideoType; 
    };
© www.soinside.com 2019 - 2024. All rights reserved.