0

I'm trying to get the name of the uploaded image file in my HTML. I tried to apply the solutions at https://stackoverflow.com/questions/1804745/get-the-filename-of-a-fileupload-in-a-document-through-javascript and https://stackoverflow.com/questions/14359913/how-to-get-value-of-img-tag. They helped me a bit but not fully. So, my img tag looks just like this:

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

and the above function looks like this:

function imgListener(imgFile){
    console.log(document.getElementById('imgPreview').src)
}

When I run this code it shows me a crazy long text with thousands of letters and digits. That's for sure not what I asked for. The console output looks something like this, but only a lot longer:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QCCRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAABJADAAIAAAAUAAAAUJAEAAIAAAAUAAAAZJKRAAIAAAADOTYAAJKSSOKbCtSjAI9aS3sUX7ZQFxnirCgdqr27Dbip1/Sk79RD+dvWmHvTt+3jrTG57VSFsKqfXFWUT5elQx9hVlc7R6U7jG7h3pjSfhQ3XimbR6VK3F5H4wXGreZxuyAevWora+kLnDZH865Zb5+qYz0rd0rVo9PkR5og8IILNu5A9a8ajH2asz6nGTdaTmjrYLh/s+8pnIwQaba6lPExEVzcIwyQPNOB+HpW2lqsibVGCRnHUjIrPvPDc0vmJhUDcZDYNdu60PDhJRleR6docryafbST8TtGC47ZrWUjIz+FY9jMPJjDENhVA29sCrsc3Y1aMTQ3buN2B9aSEnec8L61XDU9WAI6n8aYiWSTDHAx60RsNu7OTUe4Z6U9JjH0XrQBu+GwrXBbrtHQ9vesXxhdLHrF/KyjFopz6kAZrd8OyBVnYYOFGc/WvPviVqS2vh/xXdyYUpayHcOAOMVEti42PHbbXLLxNcT5ljjui5OGGNwzxipVuNQ8PTCSBSIx29favEtF1i5t4oZHJkUg/wC8MnqDXpOgePEkjWG4DzRHgux5FYuLR18y5nY9Z8P+N7a/AjdmSVh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n0k97sq2MgkXa3NPuNJim+bZzVOwJWfFdZbW/mRAsKxkrbE9bHLNpSqpGzDdjVZdKkEnPArsZNPLdF/SnR6bu5K1jruW7pWObtdJZscYroNP08RYyOatra+T2prTbKrm01OflbJXxGKyrxutWJ7oMp5/Osi5vNxIzVxvciUVYnt5grAVkePLlP7NhjZsiSeJP++pFUj9auQyZauI+IOpz3niPw5olnk3FxqVmvy88GVW5HphSePT0yR7eFi3JR6ngYt2jO72R9p20flTGNT8i4C+wx0rSj7VUX5ZpOn3uKsxtz6160t7s+dWxbhkNSDO/NRQ/ezVnvVLQC5bsNvAqwuWqrbt/kj/vZwPrQIi/dRsGI8wdv/1ZqzayR+dGQm0E/Lt6Z496q/ZtvO75fUc0+EbpU2ncVIPp6dKAOtiX5Rk5qZfz9qhh/wBWueDjpUg6jnAqhEy7RwetKOmetR/dXrmnBg2c/lQALyeOlMumPk9eKMkn2z0qO8b9ycAdPWhgZh3bwe3erEP5+lZxT/SAykFgeVLE1oQt8oyMVIyfjjmnJwx5xTP0py/e5poTP//Z

I'm using src and not value. I'm guessing that's what's causing this. but i dont know how else I could access this information,I now know that value is not used for img tag. How can I do it, so that I get just the name of the file?

sao
  • 1,835
  • 6
  • 21
  • 40
armel
  • 299
  • 3
  • 14
  • use `var img = document.getElementById('imgPreview'); console.log(img.src)` to get image src. – Mahesh S Oct 31 '19 at 15:13
  • 2
    That IS the image source; it's a data URL that encodes the entire image into a string that can be used in place of any URL. Whatever script is setting the image's source is using a data URL for it. (Try it: copy the entire data URL you're getting into your browser's address bar and press enter. You'll see the image.) – IceMetalPunk Oct 31 '19 at 15:15
  • isn't what you suggest just the same as what I'm doing above? Anyways, I tried it. Same result. – armel Oct 31 '19 at 15:15
  • As @IceMetalPunk stated, there is some library / framework / CMS that is converting your images in base64, in order to save space on the disk. There's no a trivial answer to your question – Christian Vincenzo Traina Oct 31 '19 at 15:17
  • Are you creating these image tags? You could put the src in the alt attribute, then get document.getElementById('imgPreview').alt. – Matt Kuhns Oct 31 '19 at 15:20
  • @CristianTraìna, really? I just wanna know the name of the image file the user has uploaded. I thought there must be some easy way of doing that – armel Oct 31 '19 at 15:21
  • @armel — This is why you should provide a **tested** [mcve]. I'm speculating you are using the FileReader API to read the image data, generate a data: URL and populate an `` element. There is no name there. There **is** a name in the original File object which you got the data from in the first place. – Quentin Oct 31 '19 at 15:25
  • [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/src) states that "The `HTMLImageElement` property `src`, which reflects the HTML `src` attribute, specifies the image to display in the `` element". So the fact that you're getting a base64 URI is just weird... perhaps you can create a [fiddle](https://jsfiddle.net/), so all of us can investigate further? – Fahmi Oct 31 '19 at 15:48
  • @Fahmi i agree. something weird with the image i think. – sao Oct 31 '19 at 18:11

3 Answers3

0

Try something like this:

function imgListener(imgFile){
  const el = document.getElementById('imgPreview');
  const tmp = document.createElement("div");
  tmp.appendChild(el);
  console.log(tmp.getElementsByTagName("img")[0].getAttribute("src").split("/").reverse()[0])
}
<img id="imgPreview"  src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" style="padding-left:15px;" onload="imgListener()"/>

Create a temporary item and append the image to get the attribute, I don't know if this works in your case.

sao
  • 1,835
  • 6
  • 21
  • 40
David
  • 519
  • 2
  • 11
0

this works, just tested on a local file and give the correct name. just have to familiarize yourself with the object properties on the img object.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <img id="imgPreview"  src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>
    <script>
        function imgListener(imgFile){
            console.log(document.getElementById('imgPreview').attributes[1].textContent);
        }
    </script>
</html>

let me know if that works

alternative

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <img id="imgPreview"  src="Anzeige%20erstellen-Dateien/default_offers_photo-edd8e5ff2d549a9fa1a898b23119931ebd0e745.png" width="500px" height="360px" style="padding-left:15px;" onload="imgListener()"/>
    <script>
        function imgListener(imgFile){
            let name = document.getElementById('imgPreview').attributes[1].textContent;
            let nameSplit = name.split("/");
            let lastSplit = nameSplit[nameSplit.length - 1];
            console.log(lastSplit);
        }
    </script>
</html>
sao
  • 1,835
  • 6
  • 21
  • 40
  • Hey that gives the same result as in my code, returns the image source instead of the name of the image file – armel Oct 31 '19 at 17:55
  • i tested it w a jpg instead of a png, hmmm, maybe there is a different object parameter list based on the format. let me try with a local png... – sao Oct 31 '19 at 17:56
  • works fine with a PNG too. using firefox dev editon. Might be something with your image. try testing with another png image. here is the exact on i used. `https://clipground.com/images/png-tree-clipart-3.png` – sao Oct 31 '19 at 17:59
  • i read the URL just fine too if past the URL as source and dont use a local image. console.log's just fine – sao Oct 31 '19 at 18:02
  • hmm. I've tried both with .png and jpg. doesn't make difference unfortunately – armel Oct 31 '19 at 18:05
  • try using `https://clipground.com/images/png-tree-clipart-3.png` as your image src property and see if you get the right filename. if so it might be an issue with your image – sao Oct 31 '19 at 18:07
  • also you might be getting the right info in a base 64 format, you ever try converting the text from base 64? `https://www.base64decode.org/` – sao Oct 31 '19 at 18:08
  • 1
    ok, your above code helps to show at least my src property right. But whenever I load another file it shows the image source instead of the files name. I ve tried it with several different jpg and png files... – armel Oct 31 '19 at 18:31
  • try my second option, which splits the URL to just give you the filename in the case its a path – sao Oct 31 '19 at 18:59
  • 1
    the second option returns some characters from that image source. but that doesnt look like the file's name. again it only works for the image source. BTW, thanks a lot for helping. l really appreciate it – armel Oct 31 '19 at 19:28
  • both work for me. its going to be something simple. keep working with it. maybe move the file to the same folder. Good luck! – sao Oct 31 '19 at 19:39
0

document.getElemntById('whatever the ID is').files[0].name

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 13 '22 at 06:57