Uploaded Image does not show in Safari 5.1 on Windows - javascript

I am using this tutorial to upload Image and display it. It works well in Chrome and Firefox but it is not showing uploaded image in safari. Why?
HTML
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
Javascript
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}

Open web development tools (Firebug for Firefox or CTRL+SHIFT+J in Chrome), select the image element with the element inspector and have a look at the URL that it is loading from and determine how it is different from the URL it should be loading from.
Since you're using Safari 5.1 on Windows, the FileReader API isn't supported and Safari on Windows will no longer be updated your best bet is to use a placeholder image from the server and call this battle a draw. Safari 5.1 market share on Windows is trivial at best and will only decrease as time goes on. Part of programming is knowing when to walk away from a fight.
if (window.FileReader)
{
//Your FileReader code here.
}
else
{
//Insert an image from the server here.
}

Related

How to save data in local hd with javascript?

I'm using CKEditor to create text in a website that create documents. The problem is the internet connection, the PC is far away from town and it's unstable 3G connection. I already have a routine to save a draft every ten seconds (or the time the user wish to be) in the server for safe - simple task. The problem is that if the internet goes down, the user will have to select - copy the text and try to save it locally with some text editor (maybe Word, that will make a mess).
So I'm wondering if already exists a way of to create a file and download to the local HD without remote server, just the JavaScript and navigator. Also, it might be another way to save the job but keeping CPU on and navigator open, but couldn't find in stack overflow.
I found just one non-standard API FireFox compatible:
Device Storage API
Of course, is not JavaScript standard so I don't know if it's a good idea to use right now.
Any ideas?
[Compatibility Note]
This solution uses <a> attribute download, to save the data in a text file.
This html5 attribute is only supported by Chrome 14+, Firefox 20+ and Opera
15+ on
desktop, none on iOS and all current majors except WebView on Android.
-A workaround for IE 10+ is to not hide/destroy the link generated by clickSave()and ask user to right-click > Save target As…
-No known workaround for Safari.
Also note that data will still be accessible via
localStorage.getItem()
for Firefox 3.5+, Chrome&Safari 4+, Opera 10.5+ and IE 9+ (xhr will
crash IE 8-)
I would do it like so, assuming your actual code saves the data via xhr.
function saveData() {
var xhr = new XMLHttpRequest();
//set a timeout, in ms, to see if we're still connected
xhr.timeout = 2000;
xhr.addEventListener('timeout', localStore, false);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// not a good news
if (xhr.status !== 200) {
localStore();
}
else{
document.querySelector('#local_alert').style.display = 'none';
}
}
}
//I assume you already have the part where you set the credentials
xhr.open('POST', 'your/url.php');
xhr.send();
}
//Show the link + Store the text in localStorage
function localStore() {
document.querySelector('#local_alert').style.display = 'block';
var userText = document.querySelector('textArea').value;
localStorage.setItem("myAwesomeTextEditor", userText);
}
//provide a link to download a file with txt content
window.URL = window.URL || window.webkitURL;
function clickSave(e) {
var userText = document.querySelector('textArea').value;
var blob = new Blob([userText], {type: 'plain/text'});
var a = document.createElement('a');
a.download = "myAwesomeTextEditor" + (new Date).getTime() + '.txt';
a.href = URL.createObjectURL(blob);
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
setInterval(saveData, 3000);
#local_alert {
display: none;
position: static;
width: 100%;
height: 3em;
background-color: #AAA;
color: #FFF;
padding: 0.5em;
}
body,
html {
margin: 0
}
<div id="local_alert">You're actually offline, please beware your draft is not saved on our server
<button onclick="clickSave()">Save Now</button>
</div>
<textarea></textarea>
Ps: If your user leaves the page without connection, you'll be able to get the text back via localStorage.getItem("myAwesomeTextEditor")
PPs: A more "live" example can be found here (it won't save to server but you've got the rest of the logic working). Try to disconnect , then reconnect.
Try
var editor = document.getElementById("editor");
var saveNow = document.getElementById("save");
function saveFile() {
if (confirm("save editor text")) {
var file = document.createElement("a");
file.download = "saved-file-" + new Date().getTime();
var reader = new FileReader();
reader.onload = function(e) {
file.href = e.target.result;
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
};
reader.readAsDataURL(new Blob([editor.value], {
"type": "text/plain"
}));
}
};
saveNow.addEventListener("click", saveFile, false);
<button id="save">save editor text</button><br />
<textarea id="editor"></textarea>

Dragging local image in webpage crashes Chrome

I'm working on a page where users can view/upload local files. Once the file has been selected, I'm displaying the image in the page. I've come across an issue that dragging such an image crashes my browser window (Chrome).
Here's a jsfiddle.
Simple html:
<input type='file'>
<img>
Javascript (jQuery):
$('input').change(function(){
var file = $('input').get(0).files;
var fileReader=new FileReader();
fileReader.onload = function(e){
$('img').attr('src',e.target.result);
};
fileReader.readAsDataURL(file[0]);
});
Poking around a bit more, it seems this is only a problem with large image files (such as uncompressed photos from an iPhone). This isn't necessarily a deal-breaker for the page but it is certainly annoying to accidentally drag an image and instantly crash the page.
Is there any good way to fix this?
I solved using Blob :
if (file !== undefined && window.FileReader !== undefined) {
var reader = new FileReader();
var self = this;
reader.onload = function(e) {
if (window.Blob) {
var blob = new Blob([e.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
self.setSrc({"tempUrl" : blobURL}); //using backbone this refers to a model
}
};
reader.readAsArrayBuffer(file);
} else {
if (!file)
console.error("No file prevented");
if (!window.FileReader)
console.error("Your browser is not supported");
}
As I could see, readAsDataURL kills the memory.

CamanJS - Mobile - Blank Canvas

I am having problems running the CamanJS script on mobile devices, i.e. iPad and iPhone's Safari / Chrome, and I've been trying to resolve it for days.
The test script is very simple:
1) Accepts browser file selection of image
2) Gets the image source using FileData, then drawing it into a canvas, then instantiate a Caman("#sample") object
3) Run some filter (either within onLoad of that image, or manually by clicking a button)
It works perfectly fine on all desktop browsers and the filters are also successfully applied, but when I try it on mobile devices like iOS Safari, the moment I try to instantiate the Caman object, my existing canvas #sample goes blank and reverts to the original canvas default background color, with no image loaded at all. I've tried instantiating the Caman object before image is drawn on canvas, image onLoad, or on demand after the canvas image is successfully drawn, but the end result is still the same - the canvas goes blank.
Below is my sample code, can someone please advise? Thank you for your kind assistance.
<script>
var caman = null;
function handleUpload(evt) {
var target = (evt.target) ? evt.target : evt.srcElement;
var files = target.files; // FileList object
var field = target.id;
var curCount = target.id.replace(/\D+/, "");
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
renderImage(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
}
function renderImage(imagedata) {
var canvas = document.getElementById("sample");
var ctx = canvas.getContext("2d");
// Render Preview
var previewImage = new Image();
previewImage.src = imagedata;
previewImage.onload = function() {
ctx.drawImage(previewImage, 0, 0, previewImage.width, previewImage.height);
caman = Caman("#sample", function () { this.sunrise().render(); });
};
}
function testProcess() {
//caman = Caman("#sample", function () { this.sunrise().render(); });
if (caman) {
caman.sunrise().render();
}
}
</script>
<form>
<input id="photo" name="photo" value="" type=file size="30" maxlength="50">
</form>
<canvas id="sample" width=300 height=300 style="background-color: #aaaaaa;"></canvas>
<br><br>Test Process<br><br>
<script>
document.getElementById('photo').addEventListener('change', handleUpload, false);
</script>
I had the same problem: worked on Chrome and Safari on my Mac, but did not work on Chrome or Safari on the iPhone 5s running iOS7. I solved by adding the data-caman-hidpi-disabled attribute to my canvas tag.
Try this:
<canvas id="sample" width=300 height=300 style="background-color: #aaaaaa;" data-caman-hidpi-disabled="true"></canvas>
According to the CamanJS website:
If a HiDPI display is detected, CamanJS will automatically switch to
the HiDPI version if available unless you force disable it with the
data-caman-hidpi-disabled attribute.
http://camanjs.com/guides/#BasicUsage

Is it possible to load an image into a web page locally?

The idea is to take an image from a user's machine and allow them to display the image in a webpage. I do not want to send the image back to the server.
An upload button will exist. It should just update the page content dynamically.
Can this be done with HTML5 localstorage or anything?
FileReader is capable of doing this. Here's sample code:
<input type="file" id="files" name="files[]" multiple />
<img id="image" />
<script>
function onLoad(evt) {
/* do sth with evt.target.result - it image in base64 format ("data:image/jpeg;base64,....") */
localStorage.setItem('image', evt.target.result);
document.getElementById('image').src = evt.target.result;
};
function handleFileUpload(evt) {
var files = evt.target.files; // FileList object
for (var i = 0; i < files.length; i++) {
var f = files[i];
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = onLoad;
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileUpload, false);
var image = localStorage.getItem('image');
if (image !== null) {
document.getElementById('image').src = image;
}
</script>
Yeah absolutely, providing you have a cutting edge browser (Chrome or Firefox).
You want to use FileReader and readAsDataURL(). Take a look at the third example in this tutorial:
http://www.html5rocks.com/en/tutorials/file/dndfiles/

how to validate image size and dimensions before saving image in database

I am using ASP.NET C# 4.0, my web form consist of input type file to upload images.
i need to validate the image on client side, before saving it to my SQL database
since i am using input type= file to upload images, i do not want to post back the page for validating the image size, dimensions.
Needs your assistance
Thanks
you can do something like this...
You can do this on browsers that support the new File API from the W3C, using the readAsDataURL function on the FileReader interface and assigning the data URL to the src of an img (after which you can read the height and width of the image). Currently Firefox 3.6 supports the File API, and I think Chrome and Safari either already do or are about to.
So your logic during the transitional phase would be something like this:
Detect whether the browser supports the File API (which is easy: if (typeof window.FileReader === 'function')).
If it does, great, read the data locally and insert it in an image to find the dimensions.
If not, upload the file to the server (probably submitting the form from an iframe to avoid leaving the page), and then poll the server asking how big the image is (or just asking for the uploaded image, if you prefer).
Edit I've been meaning to work up an example of the File API for some time; here's one:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadImage() {
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = document.createElement('img');
img.onload = imageLoaded;
img.style.display = 'none'; // If you don't want it showing
img.src = fr.result;
document.body.appendChild(img);
}
function imageLoaded() {
write(img.width + "x" + img.height);
// This next bit removes the image, which is obviously optional -- perhaps you want
// to do something with it!
img.parentNode.removeChild(img);
img = undefined;
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>
Works great on Firefox 3.6. I avoided using any library there, so apologies for the attribute (DOM0) style event handlers and such.
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}

Categories

Resources