Pass image src to function instead of files - javascript

So I have a webpage with two image elements. It is basically a website where you upload an image and it encrypts a secret massage with steganography. I want to show the difference that is not otherwise visible and I found Resemble.js which is a library to compare images. It gets two files as arguments and I would like to use my image sources instead of files since I don't want to save the images generated.
To sum up, I want to get rid of the requests and get my images via sources in the HTML but I don't know how to get it to work with Resemble.js since it accepts only files.
How the second image is generated:
cover.src = steg.encode(textarea.value, img, {
"width": img.width,
"height": img.height
});
The JavaScript working with files:
(function () {
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
var done = $.Deferred();
var dtwo = $.Deferred();
try {
xhr.open('GET', 'static/original.png', true);
xhr.responseType = 'blob';
xhr.onload = function (e) { done.resolve(this.response); };
xhr.send();
xhr2.open('GET', 'static/encoded.png', true);
xhr2.responseType = 'blob';
xhr2.onload = function (e) { dtwo.resolve(this.response); };
xhr2.send();
} catch (err) {
alert(err);
}
$('#example-images').click(function () {
$.when(done, dtwo).done(function (file, file1) {
if (typeof FileReader === 'undefined') {
resembleControl = resemble('./static/original.png')
.compareTo('./static/encoded.png')
.onComplete(onComplete);
} else {
resembleControl = resemble(file)
.compareTo(file1)
.onComplete(onComplete);
}
});
return false;
});
}());

Related

How to interface a DOM object when a link is pressed

I am on http://localhost:8000/index.html
When I press a link, I want it to go to localhost:8006/someAddress and select element with id='157579' AND press button with id='1787' which will cause an iframe further down my html to show something different.
I have made some pseudo code that somewhat shows what I want, but I am having a hard time converting it into something functional:
<body>
<script>
function Scenario1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
GoTo http://localhost:8006/SomeAddress
document.getElementById("157579").Select
Button("1787").Press
}
}
</script>
</body>
Is this possible to do, or is there an alternative? I understand that I have to do something with AJAX or jQuery or something similar, right?
use jquery click event when in your onload is triggered like $('#157579').click();
let xhr = new XMLHttpRequest();
xhr.open('GET', '/article/xmlhttprequest/example/load');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
$('#157579').click();
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`);
}
};
xhr.onerror = function() {
alert("Request failed");
};

How do I fetch all images in a folder with AJAX using pure JS?

I'm trying to get all the images in a folder with an AJAX request (for use in an image slider). I've found this jQuery solution which works perfectly fine, except that it uses jQuery. What would a pure JS equivalent look like? (i.e. XMLHttpRequest)
Thanks to #FZs help this is what I ended up with. Thank you!
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
You can do it without jQuery! Maybe with more code, but this should work (adapted from this post)):
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
var elements=(new DOMParser()).parseFromString(ajax.responseText,"text/html").getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()
Or, you can force XMLHttpRequest to parse document (idea from #Rainman's comment):
ajax.responseType = "document"
So the code becomes to the following:
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
ajax.responseType="document"
var elements=ajax.responseText.getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()

Getting a document Object from url of an html page

I`am working on a js file which was designed for a home page.
I would like to navigate from this page to other pages via a navigation menu bar.
The target pages are sharing the same templat(a html code), thus for going to a specific page I need to load a specific content, which is saved in a xml file, then pass its contents to the target page.
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
// Until this point I can load the specific content
// How can I get from the url of the target page
// a js document object, so that I can call getElementById(Id)
// to pass the specific content.
// For instance: Im currently opnening X1:= www.main.com
// und I would like to switch to X2 := www.targetpage.com
// target page which contains html the templat.
// The problem **document** represents currently X1
// but i would like to set it to X2 so that I can pass
// the content of xhr.responseText to it
var component = **document**.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
Thanks
Try this, I have added xhr.onload function, which populated text returned from response
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var component = document.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
You can also use onreadystatechange event instead of onload. click for more reference
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
Reference

Why might XMLHttpRequest ProgressEvent.lengthComputable be false?

I'm trying to implement a upload progress bar the HTML5 way, by using the XMLHttpRequest level 2 support for progress events.
In every example you see, the method is to add an event listener to the progress event like so:
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
Such examples always seem to assume that event.lengthComputable will be true. After all, the browser knows the length of the request it's sending, surely?
No matter what I do, event.lengthComputable is false. I've tested this in Safari 5.1.7 and Firefox 12, both on OSX.
My site is built using Django, and I get the same problem on my dev and production setups.
The full code I'm using to generate the form upload is shown below (using jQuery):
form.submit(function() {
// Compile the data.
var data = form.serializeArray();
data.splice(0, 0, {
name: "file",
value: form.find("#id_file").get(0).files[0]
});
// Create the form data.
var fd = new FormData();
$.each(data, function(_, item) {
fd.append(item.name, item.value);
});
// Submit the data.
var req = new XMLHttpRequest();
req.addEventListener("progress", function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
console.log(percentComplete);
}
}, false);
req.addEventListener("load", function(event) {
if (req.status == 200) {
var data = $.parseJSON(event.target.responseText);
if (data.success) {
console.log("It worked!")
} else {
console.log("It failed!")
}
} else {
console.log("It went really wrong!")
}
}, false);
req.addEventListener("error", function() {
console.log("It went really really wrong!")
}, false);
req.open("POST", "/my-bar/media/add/");
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.send(fd);
// Don't really submit!
return false;
});
I've been tearing my hair out for hours on this. Any help appreciated!
Hey I found the answer from #ComFreek:
I made the same mistake.
The line I wrote was:
xhr.onprogress = uploadProgress;
The correct one should be
xhr.upload.onprogress = uploadProgress;
take a look into this :
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
xhr.upload.addEventListener('progress',function(e){}) will also work.
I also had problem with sending multiple big files using AJAX (xmlhttprequest).
Found a solution and here is whole script that I use.
All you need is to place next line in your HTML page:
<input type="file" multiple name="file" id="upload_file" onchange="handleFiles(this)">
and use next script:
<script type="text/javacript">
var filesArray;
function sendFile(file)
{
var uri = "<URL TO PHP FILE>";
var xhr = new XMLHttpRequest();
var fd = new FormData();
var self = this;
xhr.upload.onprogress = updateProgress;
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function updateProgress (oEvent)
{
if (oEvent.lengthComputable)
{
var percentComplete = oEvent.loaded / oEvent.total;
console.log(Math.round(percentComplete*100) + "%");
} else {
// Unable to compute progress information since the total size is unknown
console.log("Total size is unknown...");
}
}
function transferComplete(evt)
{
alert("The transfer is complete.");
}
function transferFailed(evt)
{
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt)
{
alert("The transfer has been canceled by the user.");
}
function handleFiles(element)
{
filesArray = element.files;
if (filesArray.length > 0)
{
for (var i=0; i<filesArray.length; i++)
{
sendFile(filesArray[i]);
}
filesArray = '';
}
}
</script>
Your result will be in console

how to detect if a URL points to a SWF

Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!
You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
Update
This version will always execute the callback with a boolean value.
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
Put your logic in the isImageCallback function.
I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way.
Completely untested, basicly just an idea:
function isImage(url)
{
var http = getHTTPObject();
http.onreadystatechange = function ()
{
if (http.readyState == 4)
{
var contentType = http.getResponseHeader("Content Type");
if (contentType == "image/gif" || contentType == "image/jpeg")
return true;
else
return false;
}
}
http.open("HEAD",url,true);
http.send(null);
}
function getHTTPObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
return false;
}
I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?
If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.

Categories

Resources