HTML5 and File API in Chrome problem - javascript

I'm trying to get this piece of code work in Chrome (latest build 10.0.648.205) and it works as expected in Firefox. Here, the e.target.result of the showImage function is empty. Can anyone tell me what Am I doing wrong?
$(function () {
var dropbox = document.getElementById("dropimage");
dropbox.addEventListener("dragenter", function (e) {
this.className = "over";
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("dragleave", function (e) {
var target = e.target;
if (e && e === dropbox) {
this.className = "";
}
e.preventDefault();
e.stopPropagation();
}, false);
dropbox.addEventListener("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
var count = files.length;
if (count > 0) {
handleFiles(files)
}
}, false);
function handleFiles(files) {
$("#droplabel").html("Processing...");
file = files[0];
var reader = new FileReader();
reader.onloadend = showImage;
reader.readAsDataURL(file);
}
function showImage(e) {
$("#playerImage").attr("src", e.target.result);
$("#droplabel").html("Done");
}
});
HTML is straight-forward (I took the lines that include the scripts for simplicity):
<html>
<body>
<img id="playerImage"/>
<div id="dropimage">
<span id="droplabel">Drop file here...</span>
</div>
</body>
</html>
Also, if I try to change the dropbox.addEventListener for jQuery's $.bind, it doesn't do anything at all. Any thoughts?

The problem was that I was opening the html as a file. Chrome doesn't like that, so I resolved the problem by placing my html file in the wwwroot folder and opening it using a localhost/dnd.html address.

Related

Fix play function

I am try to develope a Macro Recorder in html and javascript , my all functions seems to work correct , but wen i press play button its not work also i have try debug and there is no errors , i cant find any error or some thing wrong , how can i fix this bug.
Here is my current code
<!DOCTYPE html>
<html>
<head>
<title>Macro Recorder</title>
</head>
<body>
<button id="start">Start Recording</button>
<button id="stop">Stop Recording</button>
<button id="play">Play Recording</button>
<button id="save">Save Recording</button>
<button id="load">Load Recording</button>
<script>
var events = [];
var isRecording = false;
document.getElementById("start").addEventListener("click", function() {
isRecording = true;
events = [];
});
document.getElementById("stop").addEventListener("click", function() {
isRecording = false;
});
document.addEventListener("keypress", function(event) {
if (isRecording) {
events.push({
key: event.key,
charCode: event.charCode
});
}
});
document.getElementById("play").addEventListener("click", function() {
events.forEach(function(event) {
setTimeout(function() {
var event = new KeyboardEvent("keypress", {
key: event.key,
charCode: event.charCode
});
document.dispatchEvent(event);
}, 500);
});
});
document.getElementById("save").addEventListener("click", function() {
var data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(events));
var downloadAnchorNode = document.createElement("a");
downloadAnchorNode.setAttribute("href", data);
downloadAnchorNode.setAttribute("download", "events.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
});
document.getElementById("load").addEventListener("click", function() {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.addEventListener("change", function() {
var reader = new FileReader();
reader.onload = function() {
events = JSON.parse(reader.result);
};
reader.readAsText(input.files[0]);
});
input.click();
});
</script>
</body>
</html>
I am try to develope a Macro Recorder in html and javascript , my all functions seems to work correct , but wen i press play button its not work also i have try debug and there is no errors , i cant find any error or some thing wrong , how can i fix this bug.
In the keypress event (which is deprecated, please don't use it) you store the key property of the event, but then in the play function you expect the code property to be present, so that's why it doesn't work.
You should learn to use the debugger, you would have found the problem immediately.

Return path location for File in Javascript/HTML

Yes, I am trying to drag and drop a file into my browser. I would like to then take the path for that file, and assign it to some variable in my JS code.
Below is my failing attempt to make it work. Please show me some example to achieve this.
<body>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
output = [];
var source = evt.dataTransfer.files();
for (i=0, f; f=source[i], i++){
outpush.push(source[i])
}
console.log(outpush[0]);
}
window.addEventListener("dragover",function(e){
e = e || event;
e.preventDefault();
},false);
window.addEventListener("drop",function(e){
e = e || event;
e.preventDefault();
handleFileSelect(e);
},false);
</script>
</body>
</html>
Issues
evt.dataTransfer.files() is not a function. It should be replaced with evt.dataTransfer.items.
Your for loop is invalid, it should be changed from
for (i=0, f; f=source[i], i++){
outpush.push(source[i])
}
...to...
for (i=0; i < evt.dataTransfer.items.length; i++){
output.push(source[i]);
}
The part inside the brackets of the for loop is invalid.
You are trying to add the file to outpush, which does not exist. You should be adding the file to the array output, which you did create.
You can not get the path of the file, as JavaScript has no access to the host computer (for security reasons). You can still manage the file though using source[index].getAsFile().
Corrected code
I have provided a jsfiddle.
<html>
<body>
<script>
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
output = [];
var source = evt.dataTransfer.items;
for (i = 0; i < evt.dataTransfer.items.length; i++) {
output.push(source[i]);
}
console.log(output[0]);
}
window.addEventListener("dragover", function(e) {
e = e || event;
e.preventDefault();
}, false);
window.addEventListener("drop", function(e) {
e = e || event;
e.preventDefault();
handleFileSelect(e);
}, false);
</script>
</body>
</html>

Change this code from FileReader() to URL.createObjectURL

I see this particular code everywhere on Stackoverflow and many suggested that it needs to be converted from FileReader() to URL.createObjectURL Doing so will make it faster and the links will be shorter. But I have yet to find a working solution. (It's an image preview script that shows image thumbs on upload).
Can somebody help me convert it?
<script>
$(window).load(function(){
function readURL() {
var $input = $(this);
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', e.target.result).show();
$newinput.after('<div class="delbtn delete_upload" title="Remove"><span class="bbb-icon bbb-i-remove2"></span></div>');
$("form").on('click', '.delbtn', function (e) {
reset($(this));
});
}
reader.readAsDataURL(this.files[0]);
}
}
$(".file").change(readURL);
function reset(elm, prserveFileName) {
if (elm && elm.length > 0) {
var $input = elm;
$input.prev('.portimg').attr('src', '').hide();
if (!prserveFileName) {
$($input).parent().parent().parent().find('input.file ').val("");
//input.fileUpload and input#uploadre both need to empty values for particular div
}
elm.remove();
}
}
});
</script>
If I understand you mean correctly, you may want to use URL.createObjectURL function like this:
// your url will look like this
// blob:http://example.com/a298356a-ad76-4353-a35f-b6e22a0e792f
var url = URL.createObjectURL(this.files[0]);
Full code:
function readURL() {
var $input = $(this);
var $newinput = $(this).parent().parent().parent().find('.portimg ');
if (this.files && this.files[0]) {
var url = URL.createObjectURL(this.files[0]);
reset($newinput.next('.delbtn'), true);
$newinput.attr('src', url).show();
$newinput.after(`
<div class="delbtn delete_upload" title="Remove">
<span class="bbb-icon bbb-i-remove2"></span>
</div>
`);
$("form").on('click', '.delbtn', function (e) {
reset($(this));
});
}
}

Can't drop image from desktop with html5

I'm newbie in html 5, and i'm trying some code for drop image from desktop, but my code doesn't work. This is my code:
script>
function OnDropTextarea(event) {
if (event.dataTransfer) {
if (event.dataTransfer.files) {
var leftbox = document.getElementById("leftbox");
for (var i = 0; i < event.dataTransfer.files.length; i++) {
var file = event.dataTransfer.files[i];
leftbox.innerHTML += file;
}
} else {
alert("Your browser does not support the files property.");
}
} else {
alert("Your browser does not support the dataTransfer property.");
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return false;
}
</script>
<section id="leftbox" ondrop="return OnDropTextarea (event);"></section>
So, please! help me
I try new code, but i can only drag and drop box in other box, not from desktop.
Another code:
<script>
function doFirst() {
mypic = document.getElementById('pic');
mypic.addEventListener("dragstart", startDrag, false);
leftbox = document.getElementById('leftbox');
leftbox.addEventListener("dragenter", function(e) {
e.preventDefault()
}, false);
leftbox.addEventListener("dragover", function(e) {
e.preventDefault()
}, false);
leftbox.addEventListener("drop", dropped, false);
}
function startDrag(e) {
var code = '<img src="/assets/Koala.jpg">';
e.dataTransfer.setData('Text', code);
}
function dropped(e) {
e.preventDefault();
leftbox.innerHTML = e.dataTransfer.getData('Text');
}
window.addEventListener("load", doFirst, false);
</script>
<section id="leftbox">
</section>
<section id="rightbox">
<img src="/assets/Koala.jpg" id="pic"/>
</section>
You need to override dragover and dragenter and prevent the default action in order for an element to qualify as a valid drop target. MDN
EDIT: The drop should work now, I think (the only difference between your code in mine seems to be the fact that I also do e.dataTransfer.dropEffect = "copy" in my dragover and dragenter handlers). I wish people were more explicit with "doesn't work" - is the drop happening, but you're not getting the file contents?
If that is the case, the issue might be the fact that you are treating a File object as if it was a string. So instead of this,
leftbox.innerHTML += file;
try this:
var reader = new FileReader();
reader.onload = function(e) { leftbox.innerHTML += e.target.result; };
reader.readAsText(file);
ondrop="return OnDropTextarea (event);"
Should be:
ondrop="OnDropTextarea()"
May be this is useful for you,but you have to use the jquery library
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload images with Jquery</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var obj = $("#dragandrophandler");
obj.on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
//$(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
});
obj.on('drop', function (e)
{ //alert('');
e.preventDefault();
/*$(this).css('border', '2px dotted #0B85A1');*/
var files = e.originalEvent.dataTransfer.files;
var data = new FormData();
var i=0,l=files.length;
for (i = 0; i < l; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
});
});
$(document).on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
//obj.css('border', '2px dotted #0B85A1');
});
$(document).on('drop', function (e)
{
e.stopPropagation();
e.preventDefault();
});
});
</script>
<style type="text/css">
#dragandrophandler {
border: 2px dashed #ccc;
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<div id="dragandrophandler">
Drop files here
</div>
<div id="meta"></div>
</body>
</html>

click event not firing in IE11

I have this js file:
function fireClick(node){
if ( document.createEvent ) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if( document.createEventObject ) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function' ) {
node.onclick();
}
}
function selectAvatar()
{
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.setAttribute('accept', "image/gif, image/jpeg");
fileSelector.onchange = function(event) {
var fileList = fileSelector.files;
//alert(fileList.length);
if (fileList.length==0) return;
reader.readAsDataURL(fileList[0]);
}
var reader = new FileReader();
reader.onload = function(e) {
var dataURL = reader.result;
//alert(dataURL);
var container = document.getElementById("avatart-container-div");
var backgroundIMgString = 'url("'+dataURL+'")';
container.style.backgroundImage=backgroundIMgString;
}
fireClick(fileSelector);
}
which is supposed to open programatically a file picker to select an imgae. While this works on FF and chrome, this does NOT work on IE (11 is my version). The picker itself doesn't show up. Tried debugging line by line but everything seems fine (no errors or exceptions). Any have an idea what might be the problem?
Taken from the comments:
You are actually only creating the element, without adding it to the DOM. You can add it to the DOM with: document.body.appendChild(fileSelector);
And in the selectAvatar function:
function selectAvatar()
{
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.setAttribute('accept', "image/gif, image/jpeg");
document.body.appendChild(fileSelector);
// do stuff
}
Also здрасти

Categories

Resources