Looking to obtain an image file from a URL entered into an input box, leading to the transformation of an image URL into a file object.
To illustrate, when selecting a random image on Google Images, you can either copy the Image or its URL.
In this scenario, the user copies the URL (e.g.,
https://pbs.twimg.com/profile_images/638751551457103872/KN-NzuRl.png
) and pastes it into the input box before clicking "add image." The goal is to locally access the image file via the URL so it can be passed onto ng-file-upload
's function Upload.dataUrl(myImageFile)
for uploading purposes.
Currently, validation checks ensure the URL is a valid image. However, the challenge lies in extracting the image itself from the provided URL.
formSubmit: function(){
var url = document.forms["imageForm"].elements["urlImage"].value;
console.log(url);
if (!$scope.checkURL(url)) {
console.log("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.")
return(false);
}
$scope.testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form now
console.log("SUCCESS!");
}
else if (result == "error") {
console.log("The image URL does not point to an image or the correct type of image.");
}
else {
console.log("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false);
},
checkURL: function(url){
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
},
testImage: function(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
Your help in resolving this issue would be highly appreciated!