Displaying image from website URL (json) to display locally in localhost - javascript

I have json feed that gives me thumbimage url.
This returns url like /webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png
Now, before /webapps/ It needs "app.toronto.ca" to get the full path. So I've replaced "localhost" into "app.toronto.ca" like so. And it gives me full path to image.
Now, the trouble is that, even though I retrieve full URL, image.src syntax will still force computer to add 'Localhost:5000/' to my perfectly assembled URL.
function displayEvent(array,i){
var image_url = array[i].calEvent.thumbImage.url;
var image =new Image();
var hostname = location.hostname;
toronto_host = hostname.replace("localhost","app.toronto.ca") +
image_url;
alert(toronto_host); //this give me pull URL path//
image.src = toronto_host;
alert(image.src);
// this gives localhost:5000/what_i_had_in_toronto_host//
document.getElementById("party_picture").appendChild(image);
};
since no image path starts with http://localhost:5000/... i can't use any image while i'm testing the site.
Any way i could assign image src with the correct url without localhost part?
thank you!

Image src attribute will always append the localhost ( or where the page originates from ), if you don't provide a complete URL ( in your case you provide everything except the protocol ).
toronto_host = hostname.replace("localhost","//app.toronto.ca") +
image_url;
// ^ appending '//' before your
// location will force the browser
// to set the protocol to the current
// one of the page.
This will make your img.src to behave as expected.

Related

Not able to display image using javascript

I am using VSCODE to make a blackjack game using HTML, CSS and javascript. I have defined a button that on clicking gives an image(that is stored in computer). Every time I refresh the live server(chrome), it says NOT ALLOWED TO LOAD LOCAL RESOURCE and FAILED TO LOAD RESOURCE: 404 not found. I am new to web development and need help with this project.
let blackjackGame = {
'you': {'scoreSpan': '#your_blackjack_result', 'div':'#your_box', 'score':0 },
'dealer': {'scoreSpan': '#dealer_blackjack_result', 'div':'#dealer_box', 'score':0 }
};
const YOU = blackjackGame['you']
const DEALER = blackjackGame["dealer"]
function blackjackHit() {
var cardImage = document.createElement('img');
cardImage.src = 'D:\Software Course\JS-Basics\Blackjack\images\Q.png';
document.querySelector(YOU['div']).appendChild(cardImage);
}
document.querySelector("#blackjack_hit_button").addEventListener("click", blackjackHit);
Every time I refresh the live server(chrome)
The web application is running from a server, even if it's one installed locally or only temporarily hosted within Visual Studio. As a result, this path won't work:
cardImage.src = 'D:\Software Course\JS-Basics\Blackjack\images\Q.png';
Because this is a file system path, not a web server URL. The browser doesn't want to mix those for security reasons. Instead, provide a URL for the file. Which might be something like:
cardImage.src = '/images/Q.png';
Finding out the URL is really up to you. But it'll be some path relative to the URL of the page being viewed in the browser.
You must use the correct local path from your computer. Then change the backslashs () to forward slashes (/) and add "file:///" before the path, so:
cardImage.src = 'file:///D:/Software Course/JS-Basics/Blackjack/images/Q.png';
function display_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Add image

Chromium createObjectUrl from Image comes out as net::ERR_FILE_NOT_FOUND

I know that my code works because I have been using it in firefox. When I switched to chrome, this code snippet has stopped working due to chrome unable to read the url generated by URL.createObjectURL().
export const image_preview = () => {
$('.js-thumbnail').off()
$('.js-thumbnail').on('change', function(event) {
// add event to each file input
const img = $(this).siblings('img')
const url = URL.createObjectURL(event.target.files[0]) // url to user's image
img.attr('src', url)
URL.revokeObjectURL(url) // free the allocated object
})
}
The url itself is generated but chromium fails to load it in my image tag.
Some posts suggests to use webkitURL api instead of URL but that didn't work either. Do you know the cause? Is this also a problem in other browsers as well?
You need to wait for the image has loaded before revoking its URL.
Image resources begin to load in a microtask after we set their src (among other reasons to allow setting crossOrigin properties after we set the src), so when the browser will read the src change, the line URL.revokeObjectURL(url) will already have been called, and the blob:// URL already pointing to nowhere.
So simply do
const img = $(this).siblings('img')
const url = URL.createObjectURL(event.target.files[0]) // url to user's image
img.attr('src', url)
img.one('load', (e) => { URL.revokeObjectURL(url); });

Replace image with the same path not working after second time in Html/Javascript

I have an application in Asp.net Core MVC in which user upload his profile image. The server side is working fine but at client side when i change the image src for first upload, it works fine but after second time the image replaced at server but at client side it shows the same. That's how i am changing the src of an image.
var src = "/up_images/profiles/" + result.data;
$("#profileImage").attr("src", src);
please note that i am replacing the existing image. In this case if src is "/up_images/profiles/137.jpg" then after uploading image the src will be the same. "137" is the user id.
if i refresh the page the image changes too.
also i have tried with some delay using timeout but it is not working.
What is the issue?
If the image path is exactly the same but resource changes, you'll want to force the request. That can easily be done by appending a query such as the current time.
$("#profileImage").attr("src", src + "?" + Date.now());
Or with template literals
$("#profileImage").attr("src", `${src}?${Date.now()}`);
You can try appending a query parameter that changes for each request, onto the end of the URL. It will get ignored by the server side, but the browser will treat it as a new request and not re-use the cached image.
Something like this:
var src = "/up_images/profiles/" + result.data + "?v=" + Date.now();
$("#profileImage").attr("src", src);

Blob images will not display in Chrome if revokeObjectURL is invoked

-----update------
I commented out the window.URL.revokeObjectURL( imgSrc ); and now the call works in all browsers. It seems like the url was being revoked too soon in Chrome. I would still be very curious to know why this is, and to know if there are any problems in anyone's opinion with the way I am handling revoking the URLs now. I now revoke the last URL as the next one is loaded with if (imgSrc) {window.URL.revokeObjectURL( imgSrc );} (imgSrc is now a global variable).
I have a web site which uses AJAX to call a CGI script, which outputs image/jpeg data, and the blob response is then set as the src of an image on the page using the createObjectURL function. At present it works in all browsers but Chrome.
In all other browsers the image is displayed, but in Chrome I get the message: Failed to load resource: the server responded with a status of 404 (Not Found) followed by a url prefixed by blob:.
I have tried using webkitURL instead, but this gives me the same error followed by webkitURL is deprecated.
This is the code of my AJAX call:
var filepath = "/babelia.cgi";
xmlhttp=new XMLHttpRequest();
xmlhttp.onload = function(oEvent) {
if (imgSrc) {window.URL.revokeObjectURL( imgSrc );}
var blob = xmlhttp.response;
if (endless) {
imgSrc = (window.URL ? URL : webkitURL).createObjectURL( blob );
document.getElementById("palette").src = imgSrc;
// window.URL.revokeObjectURL( imgSrc );
babel();
}
}
xmlhttp.open("POST",filepath,true);
xmlhttp.responseType = "blob";
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var info = "location=" + postdata;
if (!landscape) {info += "&flip=portrait";}
xmlhttp.send(info);
You can see the website here: https://babelia.libraryofbabel.info/slideshow.html
I had some issues understanding blobs as well, here are my 2 cents.
I recommend using https://github.com/eligrey/Blob.js for abstracting away browser differences when working with blobs.
When debugging chrome check out chrome://blob-internals/ for details. With the current version (47.0.2526.106) it shows the urls and the associated data or references to local files for those urls.
As soon as you revoke the url you basically tell the browser that you no longer need the data, which is good if you want to free memory, but bad if you still have references pointing to that url (e.g. an img tag).
Side note: reading your question made me solve of my own problem which was that I was seeing 404s in chrome after revoking because I still had a reference to a revoked url on an img tag.

Get full URL from a hyperlink using jQuery / JavaScript

How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return http://www.mysite.com/mypage.aspx from .
I have tried the following:
$(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).
this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.
What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.
You can create an img element and then set the src attribute to the retrieved href value. Then when you retrieve the src attribute it will be fully qualified. Here is an example function that I have used from http://james.padolsey.com/javascript/getting-a-fully-qualified-url/:
function qualifyURL(url){
var img = document.createElement('img');
img.src = url; // set string url
url = img.src; // get qualified url
img.src = null; // no server request
return url;
}

Categories

Resources