how to get latest Image from folder using javascript? - javascript

I am using jquery's Uploadify to upload images on server. Now what i am doing when user successfully upload a image, i want to replace this image with the old one. for that i am binding the image onsuccess method of uploadify, it is working fine if the image's name is always different then the previous one, but if the image's name is same as the old one it not refreshing the image, its still showing the old image.here is my code:
var WishId = "";
var ImagePath = $('[id$=hdnImgPath]').val();
var DefaultImagePath = $('[id$=hdnDefaultImagePath]').val();
$("[id$=fpFiles]").uploadify({
'swf': 'Swf/uploadify.swf',
'uploader': 'Resources/Handlers/UploadProfilePic.ashx',
'progressData': 'speed',
'cancelImg': 'Images/Grid_ActionDelete.gif',
'fileSizeLimit': '1MB',
'fileTypeExts': '*.gif; *.jpg; *.png',
'auto': true,
'multi': false,
'buttonText': 'Select',
'onSelect': function () {
WishId = $('[id$=hdnWishId]').val();
$('#lnkUpload' + WishId).show(250);
},
'onUploadStart': function (file) {
$("[id$=fpFiles]").uploadify('settings', 'formData', { 'WishID': "'" + WishId + "'" });
},
'onUploadSuccess': function (file, data, response) {
data = data.replace('"', '').replace('"', '');
if (data != '') {
alert(data);
$('[id$=imgUsersProfilePic]').attr('src', ImagePath + data);
// $('#hdnImageName' + WishId).val(data);
} else {
$('#img' + WishId).attr('src', DefaultImagePath + 'defaultProfile.png');
}
}
});
Please let me know what i have to do to display the latest image without post back, one thing more when i refresh my page its displaying the latest image.let me know where am i wrong.
Update: i know this image is coming from cache but i cannot delete the cache, if i it will delete users session too. so i need some alternate...

You can add a random number at the end of the image right after you show it there, so at the moment is still loading and work with it, is always force to load it again.
$('[id$=imgUsersProfilePic]')
.attr('src', ImagePath + data + '?' + Math.random());

You can try versioning the images once you change them.
Eg: for defaultProfile.png, replace it with defaultProfile.png?v=1 in the javascript code. This will fetch the latest image from the server and not from the cache.

Related

Fire javascript function after download asp.net

I have a method in code behind which downloads a file from server to the client. And after that I want to run a javascript function. But it does not work. It works only if the javascript function is in the button click event.
string imageFilePath = Server.MapPath("~/TireLabel.png");
Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file
Graphics g = Graphics.FromImage(bitmap);
string text = "215/45 R 20";
g.DrawString(text, drawFontArial26Bold, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter);
text = "013";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(70, 45, 0, 0), drawFormatRight);
text = "1";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(100F, 80, 0, 0), drawFormatRight);
text = "2";
g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(240, 80, 0, 0), drawFormatRight);
Bitmap bit = new Bitmap(bitmap);
bit.Save(Server.MapPath("~/TireLabel.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
Response.ContentType = "application/jpeg";
Response.AddHeader("content-disposition", "attachment; filename=" + Server.MapPath("~/TireLabel") + ".bmp");
Response.WriteFile(Server.MapPath("~/TireLabel.bmp" + ""));
ClientScript.RegisterStartupScript(GetType(), "key", "runPrint();", true); // THIS does not fire.
//Javascript function
function runPrint() {
var objShell = new ActiveXObject("WScript.Shell");
var strCommand = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
//var strCommand = "C:\\PrintLabel.exe";
objShell.Exec(strCommand);
//objShell.ShellExecute(strCommand, "","","open","1");
}
How I can make the javascript fire.
This is a hard problem, because the browser normally doesn't tell you when a download is finished. Have a look at jQuery.filedownload that allows you to download files through AJAX.
-- Edit --
Here is the code to attach jQuery filedownload to all links with the class "fileDownload":
$(document).on('click', 'a.fileDownload', function() {
$.fileDownload($(this).prop('href'))
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
return false; //this is critical to stop the click event which will trigger a normal file download
});
This assumes that the URL to the controller action is given in the href attribute of the link, and this action returns a file with return File().
The response must also contain a cookie /fileDownload to inform jquery.fileDownload that a successful file download has occured.
//jquery.fileDownload uses this cookie to determine that a file download has completed successfully
response.AppendCookie(new HttpCookie("fileDownload", "true") {
Path = "/"
});
-- Edit 2 - Changed source to show simpler example with less dependendies. Use the .done promise to trigger an action after the download was done

Tweak the load event on chrome extension

I have created a google chrome extension to replace certain images from third party websites. I have implement all the programming part but one of my requirements states that
On a slower net connection the original images should not be visible
until it’s replaced by the new images
I am not sure wether it is achievable or not. I want to know what sort of event I should attach here. Can experts give their input on this?
This is the work I have done.
// get current websites base url
var current_website = window.location.href;
//run the code on specific pages
if ($.inArray(current_website, config.target_websites) != -1) {
config.image_config.forEach(function (obj) {
var src = obj.src;
var target = obj.target;
/**find all the occurances in the <img> tag */
var key = 'img[src*="' + src + '"]';
var img = $(key);
/**replace it with the target image*/
img.attr('src', target);
/** check the inline CSS*/
$("[style*=background-image]").css('background-image', function (i, oldimg) {
return oldimg.indexOf(src) == -1 ? oldimg : 'url(' + target + ')';
});
/***check all the external styles for the image*/
$('*').each(function () {
if ($(this).css('background-image').indexOf(src) != -1) {
$(this).css('background-image', 'url(' + target + ')');
}
});
});
}
Since you're already using jQuery, if you're not opposed to a small library (7.25 KB), you can use the jQuery plugin imagesloaded.
Basic usage:
// options
$('#container').imagesLoaded( {
// options...
},
function() {
// your code to run after load
}
);
Then you could do a simple $('img').hide() on load, and $('img').show() after all images have loaded on your particular images.
You can see in the demo that it works for images which have been inserted dynamically into the page as well, which would meet your requirement for that the images of your key be hidden until replaced.
http://imagesloaded.desandro.com/

Endless looping when src value is changed in Internet Explorer

I have a problem with some javascript in Internet Explorer.
It works fine in other browsers.
I have the following method, that changes the src property of an images and when this happens a download of that image should start. See below:
for (var i = 0; i < imagesStartedDownloading.length; i++) {
if (imagesStartedDownloading[i] == false && responseItems[i] == true) {
console.log("image", i);
var url = baseurl + "/ImageDownload/?imageName=" + hash + "_" + imageDegrees[i] + ".jpg" + "&r=" + Math.random();
imagesStartedDownloading[i] = true;
images.eq(i).attr("src", url);
}
}
The problem is that in when changing this property Internet Explorer starts an endless loop of downloading images. Notice that i have put a console.log in the for-loop. I can confirm that this for-loop does not run in an endles loop. It is only run once for each image that should be downloaded. So that is not the problem.
The behaviour can actually be seen on this page: http://www.energy-frames.dk/Konfigurator. Hit F12 and check in the network tab. Make a change to image on the homepage so a download of new images is started, e.g. Bredde(Width in english), see below:
When this change is made new images are downloaded in an endless loop(it happens almost every time in IE). See below of what you could change
I have really spent a lot of time debugging in this and i cant see why it behaves like this in IE but not in all other browsers.
So does anyone have any idea why this happens? Or have some suggestions on what i could try?
EDIT:
#gxoptg
I have tried what you suggested. using "javascript:void 0" like this:
var newimg = $("<img class='rotator" + (isMainImage ? " active" : "") + "' src='javascript:void 0' />");
and this:
img.attr("src", "javascript:void 0");
gives me this error:
On the other hand, if i completely remove the line img.attr("src", "");
in the imgLoadError method, then i see that images are not downloaded in an endless loop. On the other hand they are not displayed. So am i using the javascript:void 0 wrong?
When i do the following:
img.attr("src", "void(0)");
Then the there is not endless loop but the image wont appear in IE - still works fine in chrome.
Here’s the reason:
for (var i = 0; i < totalnumberofimages; i++) {
var url = "";
var isMainImage = i == currentDragImg;
var newimg = $("<img class='rotator" + (isMainImage ? " active" : "") + "' src='' />");
newimg.on("error", imgLoadError);
newimg.on("load", imgLoaded);
imgcontainer.append(newimg);
}
Note the var newimg = $(...) line. In Internet Explorer, setting an empty src attribute on an image triggers the error event. Due to the error, the imgLoadError function is called. It looks like this:
function imgLoadError(e) {
var img = $(e.currentTarget);
var imgSrc = img.attr("src");
if (imgSrc.length > 0 && img.width() <= 100) {
setTimeout(function () {
var imgUrl = img.attr("src");
img.attr("src", "");
img.attr("src", imgUrl);
}, 200);
}
}
In this function, you run img.attr("src", ""), which sets the empty src attribute, triggers the error event, and calls imgLoadError function again. This causes the endless loop.
To prevent the error (and therefore the endless loop), set image source to "javascript:void 0" instead of "" in both code pieces. This source is valid and should work properly.
(According to comments, all the code is located in /Assets/Scripts/directives/image.rotation.directive.js file.)
An alternative solution is to set the src attribute to a valid, minimal, Base64 encoded image, as in http://jsfiddle.net/leonardobraga/1gefL8L5/
This would avoid triggering the endless error handling and it doesn't impact the code size that much.

Firefox wont reset jquery created element

This probably is a duplicate but I don't know how to express what is happening in a title description.
I have an image element which i delete and re-create with the click of a button, basically i apply filters with php to an image, and delete the previous element to replace it with the new image to display the new filter.
the code to create the element:
function pictureReset(data) {
$( ".filteredImg" ).remove();
var elem = document.createElement("img");
elem.setAttribute("class", "filteredImg");
elem.setAttribute("height", "328");
elem.setAttribute("alt", "");
elem.src = 'contest/filtered_'+tempFilePath;
document.getElementById("filteredImgContainer").appendChild(elem);
}
the code to apply the filter: (i have several filters but the code is the same, they just call a different php file
$('#sepia').click(function () {
var filePathName = tempFilePath;
$.ajax({
type: 'POST',
url: 'php/sepia.php',
dataType : 'text',
data: {
FilePath : filePathName
},
success: function (data) {
pictureReset();
}
}).done(function(response){console.log(response);});
});
now the problem is although it works fine on chrome, i.e. when i click the button the old image is removed and replaced with the new filtered image, on firefox although it refreshes, somehow it retrieves the old image (even though it doesn't exist because on the server if i retrieve the image the filter is applied), and displays the old filter instead of the new one. Any ideas as to why this is happening??
Apart from adding the parameters, you can also improve the code. Since you are already using jQuery.
You can replace this code:
function pictureReset(data) {
$( ".filteredImg" ).remove();
var elem = document.createElement("img");
elem.setAttribute("class", "filteredImg");
elem.setAttribute("height", "328");
elem.setAttribute("alt", "");
elem.src = 'contest/filtered_'+tempFilePath;
document.getElementById("filteredImgContainer").appendChild(elem);
}
With:
function pictureReset(data) {
var elem = $('<img class="filteredImg" alt="" style="height:328px;" src="contest/filtered_' + tempFilePath + '?t="' + $.now() + ' />');
$("#filteredImgContainer img.filteredImg").replaceWith(elem);
}
I used jQuery replaceWith for this code.

Strip all images with data.replace?

I'm using a script to retrieve content from an external website, and the date is returned with certain elements stripped out so that they don't interfere with the page I'm pulling the data to. However, when I view my page with the error console open, I am receiving 404s on all images. Is there anyway I can strip out all the images from the script so that I'm just getting the text (which is still in its formatted tags)?
$(document).ready(function () {
var container = $('#target');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"
+ "q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(url)
+ "%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#target').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
return data;
}
doAjax('mywebsite');
});
Option 1:
You can strip the images by adding this line to filterData() function:
data = data.replace(/<img[^>]*>/g, '');
This will replace all strings starting with <img and then containing zero or more characters other than > with an empty string.
Option 2:
You can use jQuery to remove the elements. Insert this before container.append():
justTable.find("img").remove();
This will find all img elements inside the table and remove them.
Alternative:
Some images are not available because their URL is relative. If you have <img src="logo.png"> on http://example.com/page.html then browser is loading the image from example.com/logo.png. If you include the same <img> tag to your page http://own.com/my.html then browser will try to load own.com/logo.png.
You can fix this issue by changing the src attribute of the images to include the domain you retrieved the page from.
Example (not fully tested, may need modifications):
// copy everything for url except the string after last "/" character
// so if url == http://example.com/page.html then path == http://example.com/
var path = url.match("(.+/)[^/]+$")[1];
// modify all local images (value of src attribute not starting with "http://")
justTable.find('img').not('[src^="http://"]').attr('src', function() {
return path + $(this).attr('src');
});

Categories

Resources