[英]how to include an image file knowing only name and not extension?
I am trying to set an image source by a variable name 'fileName'. 我正在尝试通过变量名'fileName'设置图像源。 I only know file name and don't know extensions.
我只知道文件名,不知道扩展名。 extensions may be .jpg, .png, .bmp etc. How i can achieve for different extensions?
扩展名可以是.jpg,.png,.bmp等。我如何实现不同的扩展名? Here is my code for .jpg extension.
这是我的.jpg扩展名代码。
'<img src="../assets/images/logos/' + fileName + '.jpg" width="60" height="40">' +
Without knowing the extension you can only do it with multiple requests or with php. 在不知道扩展名的情况下,您只能对多个请求或php进行扩展。
JS: JS:
function findExtension(path ,img, name) {
img.src = path + name ".jpg";
img.onerror = function() {
img.src = path + name ".png";
img.onerror = function() {
img.src = path + name ".gif";
};
};
findExtension("pictures/", document.querySelector("XYZ"), "image1");
PHP: Call a Php file and use glob() to find the file with its extension PHP:调用一个Php文件,并使用glob()查找带有扩展名的文件
//Name php file something like: "findExtension.php"
//In Js define the src to the phpfile and add the filename as Get parameter
<img src="findExtension.php?filename=pictureXYZ">
$filename = $_GET['filename'];
$result = glob ("./pictures/" . $filename . ".*");
if (!empty($result)) {
header("Location: /pictures/" . basename($result[0]));
} else {
//File does not exists
}
I dont think there is any function like glob() in JS. 我认为JS中没有glob()之类的函数。 This is based on the nature of js it cant directly work with the filesystem on the server.
这基于js的性质,它无法直接与服务器上的文件系统一起使用。 It would be different if your using node.js as backend.
如果您使用node.js作为后端,那将有所不同。 Then this could be easily done.
然后可以很容易地做到这一点。
Use onerror
to try different possibilities. 使用
onerror
尝试不同的可能性。 The example below starts with "filename.jpg" then tries "filename.png". 下面的示例以“ filename.jpg”开头,然后尝试“ filename.png”。
<img
src="../assets/images/logos/filename.jpg"
onerror="this.onerror=null;this.src='../assets/images/logos/filename.png'"
width="60"
height="40"
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.