Check if image exists without error message - javascript

Through (native) javascript, i want to check if an image exists. I have found this script:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
from this question. However, everytime i run this, it throws me a HEAD error message whenever it does not find an image (in the console). Can i get rid of this error whenever it fails to find something?
The onload/onerror solution in the comments at the linked question also give me the same issue, with reporting errors.

Try this
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
// Sample usage
var imageUrl = 'image_url';
imageExists(imageUrl, function(exists) {
alert(exists);
});
check out Checking if image does exists using javascript

Related

How to save a Google Street View static image to Firebase Storage [duplicate]

I'm trying to create a copy of an image (which is located at a url), and save it to Firebase's storage facility. I want to store the actual image file and not just the url. If I understand correctly, I first need to convert the image at the url to a blob or file and then upload the data to the Firebase storage.
This is my current attempt with Javascript:
function savePicture(){
var url = ["http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg"];
var blobpic = new Blob(url, {type: 'file'});
console.log(blobpic);
var user = firebase.auth().currentUser;
if (user != null) {
var userid = user.uid;
var ref = firebase.storage().ref(userid + "profilePhoto");
ref.put(blobpic).then(function(snapshot) {
console.log('Picture is uploaded!');
console.log(snapshot);
var filePath = snapshot.metadata.fullPath;
document.getElementById('picTestAddress').innerHTML = ""+filePath;
document.getElementById('picTestImage').src = ""+filePath;
});
}else{
console.log("Something went wrong, user is null.");
}
}
I have two HTML tags like this:
<div id="picTestAddress"></div>
<img id="picTestImage" />
I'm pretty sure this is only saving the url and not the physical image.
The "picTestAddress" gets filled in with "qAjnfi387DHhd389D9j3r/profilePhoto", and the console shows the following error for "picTestImage": GET file:///android_asset/www/qAjnfi387DHhd389D9j3r/profilePhoto net::ERR_FILE_NOT_FOUND
I'm using Firebase for Web and Cordova. And I'm testing the app on my android phone.
I understand that the error is because it's looking for the image on my phone's local file system. This makes sense to me, so I thought I could fix this by appending my app's address to the beginning of the filePath (eg: document.getElementById('picTestImage').src = "https://firebasestorage.googleapis.com/v0/b/MY_APP.appspot.com/o/"+filePath;).
To find the correct path, I navigated to the file's location in the Firebase console and copied the "Download url" address - but when I checked this (by entering it into my web browser) it loaded a white page which contained one line of text, which was the original url: "http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg"
So now I think I've just saved the url to the storage instead of the actual image file.
I've been following the Firebase docs, and I think I have the uploading part working correctly, but I think I'm failing when it comes to converting the url to the blob/file with Javascript.
I've looked through some other questions, such as this one: How to store and view images on firebase? and was going to follow the example here: https://github.com/firebase/firepano but it says that it's now a legacy example and I can't seem to find an updated version in Firebase's samples section.
Any advice or help with how to do this would be really appreciated.
Thank you in advance!
Looks good, though I'd also consider a promisified version:
function getBlob(url) {
return new Promise(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event){
var blob = xhr.response;
resolve(blob);
};
xhr.onerror = reject();
xhr.open('GET', url);
xhr.send();
}
}
function storageURLForPhoto(oldURL, newName) {
getBlob(oldURL)
.then(function(blob) {
var picRef = firebase.storage().ref().child(newName);
return picRef.put(blob)
})
.then(function(snapshot) {
return snapshot.downloadURL;
});
.catch(function() {
// handle any errors
})
}
Little easier to reason about :)
The following works:
function savePhoto(){
var url = "http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg";
// First, download the file:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
// Get the current user:
var user = firebase.auth().currentUser;
if (user != null) {
var userid = user.uid;
// Define where to store the picture:
var picRef = firebase.storage().ref(userid + "/profilePhoto");
// Store the picture:
picRef.put(blob).then(function(snapshot) {
console.log('Picture uploaded!');
// Now get image from storage and display in div...
picRef.getDownloadURL().then(function(pic) {
var userspic = pic;
document.getElementById('picTestImage').src = userspic;
}).catch(function(error) {
console.log("There was an error: "+error);
});
});
}else{
console.log("We weren't able to confirm there is a current user, something went wrong.");
}
};
xhr.open('GET', url);
xhr.send();
}

XMLHttpRequest detecting 404 (Not Found)

If the URL is correct (file.dat exists), this works great (the file length matches). If it is wrong I will see a very small file length and I will not see the xhr.onerror.
How can I detect that the URL was incorrect?
var xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = ()=> {
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
xhr.addEventListener("error", () => { console.error('xhr.onerror',e) })
xhr.open("GET", "file.dat")
xhr.send()
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
I do see a stacktrace in the console pointing to xhr.send()
GET http://localhost:8080/file.dat 404 (Not Found)
A try catch around both open and send does not catch any exceptions.
Files are served by WebpackDevServer (I hope that should not matter though).
You can check the status of the response object.
// Not using arrow function because I don't want the lexical `this`
xhr.onload = function() {
if (this.status === 404) {
// not found, add some error handling
return;
}
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
Credit to https://developer.appcelerator.com/question/129410/xhr-request-cant-check-for-error-for-404-page-or-other-errors
Using https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-status:
XmlHttpRequest objects (you have one in the variable xhr) have a read-only property status that you can use to get the status text once it's loaded.

Status Code 304

I am new to Javascript and server-side programming. I am trying to send a GET request to load an image from my blog: http://jsafaiyeh.github.io/img/suw_background.png
function imgLoad(url) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest({mozSystem: true});
request.open('GET', url);
request.responseType='blob';
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
resolve(request.response);
} else {
reject(Error('Image did\'t load successfully; error code '+ request.statusText));
}
};
request.onerror= function() {
reject(Error('There was a network Error'));
};
request.send();
});
}
var body = document.querySelector('body');
var myImage = new Image();
imgLoad('http://jsafaiyeh.github.io/img/suw_background.png').then(function response() {
var imageURL = window.URL.createObjectURL(response);
myImage.src = imageURL;
body.appendChild(myImage);
}, function(Error) {
console.log(Error);
});
I get status code 304. However, the image still does not load onto the page. Any help would be appreciated.
You have wrong function signature. It should be like this:
imgLoad('http://jsafaiyeh.github.io/img/suw_background.png').then(function (response) {
var imageURL = window.URL.createObjectURL(response);
myImage.src = imageURL;
body.appendChild(myImage);
}, function(Error) {
console.log(Error);
});
Working demo on JSFiddle(at least in Chrome).
Instead of passing named function, called response you probably wanted response to be in argument list. So, instead of function response(), you need function (response). You didn't get error that response was undefined, because it actually was declared, but it wasn't expected result from promise, but function.

JSON file cannot be found in javascript

I am attempting to load a JSON file from javascript but i keep getting the following error even though the path is correct
[HTTP/1.1 404 Not Found 2ms]
this is the code i am using to load it
loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'Assets/test.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
window.onload = function () {
var canvas = <HTMLCanvasElement> document.getElementById('Can');
context = canvas.getContext('2d');
load = new preload.AtlasLoader();
load.loadJSON(init);
}
function init(response) {
image2 = JSON.parse(response);
}
thanks in advance
i found the answer in this thread:
https://stackoverflow.com/questions/19516829/allow-loading-of-json-files-in-visual-studio-express-2013-for-web
it was a configuration issue with IIS and you just need to add the lnes posted in the answer in that question.

XMLHttpRequest that is being Aborted

I'm looking over a bit of code that deals with XHR. It looks like the first XHR.send() is being done successfully and then the subsequent one is Aborted before it gets to it's .send()
Quick in dirty:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
myXHR = new Array();
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
What could be happening that would cause Firebug to show Abort before the second .send() is done?
Try this:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
var myXHR = [];
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
When I run this code I get TypeError: myXHR[i] is undefined (on the stock firefox 20 install on my mac... what version are you on)?
At any rate, I can see one issue with this (i.e. myXHR[i] will be undefined...) that might also apply to you, in particular with:
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
Because this is triggered asynchronously i will have been incremented to 2, which is of course going to be outside the bounds of the two element myXHR array. Have you tried closing over the value of i, like so:
myXHR[i].onload = (function(i) {
return function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
}
})(i);
Because once I correctly save that i value in that function body this code will succeed for both calls.
I know this isn't the exact issue you're having, but I think it will be an issue regardless so you may as well give it a go right? It's not as though there have been a huge number of other answers unfortunately.
hope this helps..
Found out what was happening.
The XHR was being aborted because there was no return value from the webserver that the request was being sent to. The web server is a custom based one that we seem to be using the someone changed the code so that it wasn't sending a 200 Success OK even if the data sent to it had no data coming back.
All good now. Thanks for the help.

Categories

Resources