Finding the src of an image via Javascript - javascript

I found the answer to my question via a simple Google search, although, there is a slight problem that I ran into.
So far, I have an image on my HTML page with the ID of newAvatar. I am attempting to find this image via its ID, and save it's source into a variable, then eventually into an XML document to be used later on.
When I save this source into a variable, or alert it for checking purposes, it is displaying the full source, which is unusual. For example, I am running my site on a WAMP server, so the variable is saving as:
http://localhost/uploads/newUploadedImage.jpg
When in reality, the source should be plain and simple, uploads/newUploadedImage.jpg
The image tag is
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;" id="newAvatar"/>
The way i am checking the source is
alert(document.getElementById('newAvatar').src);
Any idea how to get rid of the first lot of junk?
All help is greatly appreciated!

By using #DavidThomas comment before, I managed to get it working. This is what i changed my alert to:
alert(document.getElementById('newAvatar').getAttribute('src'));

var hostname = document.location.hostname;
var url = 'http://' + hostname + '/';
var src = document.getElementById('newAvatar').getAttribute('src'); //'uploads/newUploadedImage.jpg'
var image = src.split('/')[1];
console.log(url);
console.log(image);

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<img src="uploads/newUploadedImage.jpg" width="60px" height="60px;"
id="newAvatar"/>
and
$(function()
{
alert($('#newAvatar').attr('src'));
});

Related

On Windows and with React: What can I do to get the full path of a browsed file? [duplicate]

How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

document.getElementById.style.backgroundImage not working

I want to assign different background images to a div depending on the page's address, so for example, if my url is http://www.mywebsite.com/mysubdirectory/ I use the following code:
if(document.URL.indexOf("mysubdirectory") >= 0){
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
}
But it's not working. I even added a bogus document.write command just to make sure the rest of the code was ok and sure enough the bogus line showed up in my browser. Is there something I'm overlooking?
EDIT: Thank you all for your answers - when I use body instead of getElementById("wrapper") in my code, the image shows up, so I doubt it's a path-related issue. I trued adding an onload attribute to the body tag but it's still not working with getElementById. Any ideas?
Your
document.getElementById("wrapper").style.backgroundImage = "url('bg-wrapper.jpg')";
code is correct.
It works fine in this jsfiddle: http://jsfiddle.net/hUuN5/
Are you sure the image is correct. Remember that the path to the file is relative to the location of the current page. NOT the css directory
I'm using Chrome 29.0.1547.66 and none of the anwers worked either.
So I tried:
document.getElementById("wrapper").style.backgroundImage = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
It worked taking off the quotation marks from the image url.
Here working as well: http://jsfiddle.net/xEujg/
html css backgroundimage javascript
Try this, I think the image url is wrong most likely. You probably need a relative path of sorts:
document.getElementById("wrapper").style.backgroundImage = "url('/bg-wrapper.jpg')";
Specifying a protocol worked for me in chrome. I couldn't get it to work using the catch all '//'. It had to be 'http://' I'm assuming it must match whatever protocol was used to load the page or iframe.
for example
element.style.backgroundImage="url(http://somedomain.com/images/myimage.jpg)"
or
element.style.backgroundImage="url('http://somedomain.com/images/myimage.jpg')"
worked for me.
If anyone is still interested in this. Here is a solution:
document.getElementById("wrapper").style.background = "url(http://media.nu.nl/m/m1fz6dwa6h3w.jpg)";
This works for me:
var pointer = "url(\'/" + imageArray[imageCounter].toString() + "\')";
document.body.style.backgroundImage = pointer
After spending a bit of time on this, it was the browser's engine parsing the CSS. No good errors in the console.
The solution is to not do everything on the same line.
You have to create a variable, assign it the url and then pass it.
let bg = "url('" + imgUrl + "')";
document.getElementById("wrapper").style.backgroundImage = bg;

how to get variable's value from URL and pass to all the links on the whole site?

I am trying to get a variable from a URL,
for example if the users can link to this page: www.example.com?var1=blabla&var2=blabla
and there are many links on this site www.example.com.
What I want is no matter where my users click, they will always see the link appended with 2 variables they got from this link www.example.com?var1=blabla&var2=blabla
for example: if there is another link
<a href="www.example.com/page1.php"/>Go to page1</a>
on www.example.com?var1=blabla&var2=blabla, they will go to page www.example.com/page1.php?var1=blabla&var2=blabla.
This is my code:
<script type="text/javascript">
$(document).ready(function() {
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
var links = $('a');
links.each(function(){
var curLink=$(this);
var href = curLink.attr('href');
var newhref = href +'?'+ hashes;
curLink.attr('href',newhref);
});
});
</script>
My question is: I can only make all the links on the same page append those 2 variable. If the users go to another page, it won't do the same thing, because there is no script on it... but I can't add same script on every pages...
And another question, I want to clear the things after question mark and append the new ones.. is that possible to do that?
Thanks!
Your code looks good to me. And from your question it appears that your problems lie outside this.
My question is: I can only make all the links on the same page append
those 2 variable. If the users go to another page, it won't do the
same thing, because there is no script on it... but I can't add same
script on every pages...
If you can't run your script on every page then you can't modify the url's. You will need to do it server side. If you can't do it server side then you are out of luck.
And another question, I want to clear the things after question mark
and append the new ones.. is that possible to do that?
Yes, that is certainly possible. To strip the querystring use the following code.
var strippedHREF = window.location.href.substring(0, window.location.href.indexOf('?'));

changing img src with JQuery but leave pathing info intact?

I'm using JQuery to switch out an image src thusly:
$("#myImg").attr("src", "../../new.gif");
notice the relative pathing on the new src. Unfortunately, this isn't portable when I deploy my app. In my MVC app I'm using a ResolveUrl() method that will fix the pathing problem for me so it's portable, but now my JQuery image src swapper doesn't work right since it now switches the correctly resolved path to a broken relative one.
<img id="myImg" src="<%=ResolveUrl("~/Images/transparent.gif")%>" />
What I want is for JQuery to just flip the actual filename and leave the path untouched. My first thought would be to
// pseudocode javascript jquery on my thought on how to approach this prob
var oldFullPath = $('#myImg").GetTheImgSrc;
var newFileNameWithPathIntact = someRegexAddNewFileNameWithOldPath
$("#myImg").attr("src", newFileNameWithPathIntact);
but that seems rather gross and un-JQuery to me. Anyone got a better way?
you could use something like this:
var oldImage =$("#myImg").attr("src");
var imagePath = oldImage.slice(0, oldImage.lastIndexOf("/")) + "/new.gif";
$("#myImg").attr("src", imagePath );
EDIT: better code...:)
You can use the resolveurl right in the javascript:
$("#myImg").attr("src", "<%=ResolveUrl("~/Images/new.gif")%>");
That of course assumes that you've included the javascript right in the view. If you have a requirement that this script must live in a separate script file from the html request, then you can just have a view which is a javascript file ... and just reference that URL in the script src:
<script language="javascript" src="<%= Url.Action("MyMethod") %>" />
why not just use a variable for the root of the app that you can use for these types of situations.
var root = "<%=ResolveUrl("~/") %>";
Now you can easily construct your image path
$("#myImg").attr("src", root + "images/" + fileName);

Categories

Resources