如何在我的 HTML 中获取图像文件的名称

我试图在我的 HTML 中获取上传的图像文件的名称。我尝试在https://stackoverflow.com/questions/1804745/get-the-filename-of-a-fileupload-in-a-document-through-javascript和应用解决方案https://stackoverflow.com/questions/14359913/how-to-get-value-of-img-tag。他们帮助了我一点,但并不完全。所以,我的 img 标签看起来像这样:


 <img id="imgPreview"  src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>

上面的函数看起来像这样:


function imgListener(imgFile){

    console.log(document.getElementById('imgPreview').src)

}

当我运行这段代码时,它向我显示了一个包含数千个字母和数字的疯狂长文本。这肯定不是我要求的。控制台输出看起来像这样,但只有更长的时间:


我正在使用src而不是value. 我猜这就是造成这种情况的原因。但我不知道我还能如何访问这些信息,我现在知道它value不用于 img 标签。我该怎么做才能只得到文件的名称?


喵喵时光机
浏览 533回答 2
2回答

慕娘9325324

这有效,只是在本地文件上进行了测试并给出了正确的名称。只需要熟悉 img 对象上的对象属性。<!DOCTYPE html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; </head>&nbsp; &nbsp; <img id="imgPreview"&nbsp; src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function imgListener(imgFile){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(document.getElementById('imgPreview').attributes[1].textContent);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></html>让我知道这是否有效选择<!DOCTYPE html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; </head>&nbsp; &nbsp; <img id="imgPreview"&nbsp; src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function imgListener(imgFile){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let name = document.getElementById('imgPreview').attributes[1].textContent;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let nameSplit = name.split("/");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let lastSplit = nameSplit[nameSplit.length - 1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(lastSplit);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></html>

泛舟湖上清波郎朗

尝试这样的事情:function imgListener(imgFile){&nbsp; const el = document.getElementById('imgPreview');&nbsp; const tmp = document.createElement("div");&nbsp; tmp.appendChild(el);&nbsp; console.log(tmp.getElementsByTagName("img")[0].getAttribute("src").split("/").reverse()[0])}<img id="imgPreview"&nbsp; src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" style="padding-left:15px;" onload="imgListener()"/>创建一个临时项并附加图像以获取属性,我不知道这是否适用于您的情况。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript