Reputation: 2664
In the large amount of similar questions, I wasn't able to really find what I need, despite it seems to be very common...
I have a user profile Form. So the user can upload an avatar. It uses a common 'Browse...' button but this one will inform the server on the next submit.
So I would like to retrieve the local image filename and directory path to immediately display the selected image.
<img src="" id="image_to_display" class="img-responsive" alt=""/>
<form enctype="multipart/form-data" method="post" accept-charset="utf-8" role="form" action="/pros/sites/add">
<input class="form-control" value="POST" type="hidden" name="_method" id="_method" />
<fieldset>
<div class="form-group file">
<input type="file" name="logofile" onchange="loadImg('logofile');" id="logofile">
</div>
.....
</fieldset>
.....
</form>
From document.getElementById("logofile"), I can only get the image name, not the pathname.
How to do it?
Upvotes: 3
Views: 3395
Reputation: 5802
From document.getElementById("logofile"), I can only get the image name, not the pathname.
That's because you are grabbing the element within the DOM, that element doesn't know about where the file was on the system, it just knows there is a file now that the DOM can look at (where it's at isn't relevant right now).
You are overcomplicating the problem.
You don't need to look for the image on the user's system to display it.
Simplify your problem and do something like what others have shown here on stackoverflow.
The solution:
This answer: https://stackoverflow.com/a/27165977/1026898 does exactly what you want.
image_to_display
. You set this with element.src
) to the image that was selected in the form (this is the image itself).Using your code:
<img src="" id="image_to_display" class="img-responsive" alt=""/>
<form enctype="multipart/form-data" method="post" accept-charset="utf-8" role="form" action="/pros/sites/add">
<input class="form-control" value="POST" name="_method" id="_method" />
<fieldset>
<div class="form-group file">
<input type="file" name="logofile" id="logofile" onchange="loadFile(event)">
</div>
.....
</fieldset>
.....
</form>
<script>
var loadFile = function(event) {
var output = document.getElementById('image_to_display');
output.src = URL.createObjectURL(event.target.files[0]);
};
</script>
Upvotes: 2
Reputation: 32058
You won't be able to get the path name because it's a privacy issue for one thing and you won't be able to assign it to an <img src
anyway due to cross origin rules. You need to look into using FileReader
although it requires relatively modern browsers (Chrome, Firefox, IE 10 ...)
Upvotes: 0