This is my HTML:
<input type="file" id="browse" name="browse" size="" placeholder="Photo" checked="checked" class="upload"/>
<input type="button" onclick="javascript:onbrowse()" class="unknown" value=""/>
And my JavaScript:
$(function() {
$(".upload").change(function () {
var fileObj = $(this).get(0);
var fileName;
if (fileObj.files) {
fileName = fileObj.files.item(0).getAsDataURL()
} else {
fileName = fileObj.value;
}
$(".unknown").css("background-size", "100px 100px");
$(".unknown").css("background-image", "url(" + fileName + ")");
});
});
function onbrowse() {
document.getElementById('browse').click();
}
I have two problems:
onclick doesn't work in Chrome and
getAsDataURL() doesn't work in Chrome and IE
Can you help me?
IE does not yet support the File API. Anyhow, you need to use a FileReader to read a file. Also, the file is not its file name (your variable naming is a little ambiguous).
The click delegation to the file input works just fine.
http://jsfiddle.net/fKQDL/
file = fileObj.files[0];
var fr = new FileReader;
fr.onloadend = changeimg;
fr.readAsDataURL(file);
Bind the button's behavior with jQuery
jQuery('input[type="button"].unknown').click ( onbrowse );
Related
at this moment my script downloads html file with name(1), name(2) etc. I wonder if I can change this script to update local file and add value instead of downloading. Or second option can I somehow force html to look for file "INCFINDERdb("highestvalue").html" ?
function save() {
var htmlContent = [document.getElementById('saveinc').value];
var bl = new Blob(htmlContent, {
type: "text/html"
});
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = "INCFINDERdb.html";
a.hidden = true;
document.body.appendChild(a);
a.innerHTML = " random ";
a.click();
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('click-me3').addEventListener('click', save);
});
<input type="text" id="saveinc">
<button class="button" id='click-me3'> Save INCs to ignore </button>
<div class="info-box">
IGNORUJEMY TE CI
<iframe src="/INCdb/INCFINDERdb.html" title="description"></iframe>
</div>
Later on I want to add remove option also with update does document.removeElement will work?
chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {
suggest({ filename: '..', conflictAction: 'overwrite' });
});
Fixed my problem
I want to open a file in Javascript that the user selects from the local filesystem. I can get the file name but I don't know how to open it.
<form action='' method='POST' enctype='multipart/form-data'>
<input id="archiveFile" type='file' name='userFile'><br>
<script>
archiveFile.onchange = function (e)
{
console.log(archiveFile.value);
// open the file here
}
</script>
</form>
You need for the HTML5 FileReader Api, further information are there: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
here is a polyfill using Flash: https://github.com/Jahdrien/FileReader
This is a very well-made article: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
it explains almost everything.
working example:
function FileReaderCtrl() {
var self = this;
var field = document.getElementById('fieldFile');
var result = document.getElementById('result');
self.readFile = function(event) {
var res = event.target.result;
var image = '<img src="'+ (res || '') +'"/>';
result.innerHTML = image;
console.log(image);
};
field.onchange = function(event) {
var files = field.files;
var reader;
if(files.length < 1) {
return;
}
reader = new FileReader();
reader.onload = self.readFile;
reader.readAsDataURL(files[0]);
}
}
document.addEventListener('DOMContentLoaded', FileReaderCtrl);
#result {
width: 200px;
height: 200px;
background: lightcoral;
margin: 1em auto;
}
img {max-width: 100% }
<label for="fieldFile">Select an Image:<br><input type="file" id="fieldFile"/></label>
<div id="result"></div>
Substitute archiveFile.files for archiveFile.value. The value of an input type="file" element is not a FileList or File object
For historical reasons, the value IDL attribute prefixes the file
name with the string "C:\fakepath\"
archive.files would be the FileList object, from which you can iterate the selected File object or objects if multiple attribute is set at input type="file" element. For example, archiveFile.files[0] to view properties of individual File object
<form action='' method='POST' enctype='multipart/form-data'>
<input id="archiveFile" type='file' name='userFile'>
<br>
<script>
archiveFile.onchange = function(e) {
console.log(archiveFile.files, archiveFile.files[0]);
// open the file here
}
</script>
</form>
I am working on an image uploader and I am currently trying to build up an image preview before the upload is done. I have this HTML code:
<input type="file" id="id_imatgeNewPeces"></input><br></br>
<img id="previewing" src="" />
Then I add a listener to the input like this:
document.getElementById('id_imatgeNewPeces').addEventListener('change', this.handleFileSelect, false);
And finally the function handleFileSelect:
handleFileSelect: function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
sap.m.MessageToast.show("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
},
I don't know why when I select a file which is not an image it displays the message but when I do select an image when the method onload ends no image is displayed and in addition it seems that the listener has been lost because no further calls are done when if I select another image.
The funny thing is that if I place a breakpoint on line '$('#previewing').attr('height', '230px');' I can see the image but when I continue it disappears. In addition when the method onload ends the fileinput "resets" I mean that it says that it has no selected files.
Besides being a old question, I've found that your code is working as expected:
I just don't undestand why use a native addEventListener() when you are using jquery for DOM manipulation, being easily replaced by:
$("#id_imatgeNewPeces").change(handleFileSelect);
var handleFileSelect = function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
console.log("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
};
$("#id_imatgeNewPeces").change(handleFileSelect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="id_imatgeNewPeces">
<br/><br/>
<img id="previewing" src="" />
I'm working on an HTML widget which will be embedded in an iBook in iBooks Author for the iPad.
I've got a simple button to trigger image capture on an iPad and all is working fine.
<div id="zeroDiv">
<input type="file" id="getPic" accept="image/*">
</div>
<div id="picWrapper">
<img id="image">
<div id="buttDiv">
<button id="picButt"><span class="buttText">Insert image</span>
</button>
</div>
</div>
and
$('#picButt').click(function () {
$('#getPic').trigger('click');
});
$(document).ready(function () {
$("#getPic").on("change", gotPic);
$("#image").load();
});
function gotPic(event) {
$("#image").attr("src", URL.createObjectURL(event.target.files[0]));
$("#picButt span").text("Change image");
}
fiddle at https://jsfiddle.net/mikawaben/cq2yrh2z/
However, when the user moves off a page and returns, the image is lost as the page reloads. I need to store the image in localStorage.
I know that the fiddle at http://jsfiddle.net/VXdkC/2/ (courtesy of Musa on this site) holds code which could be the key for me.
$('#addNote').click(function () {
var Title = $('#title').val();
var Message = $('#message').val();
var pic = document.getElementById("file").files[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>"+ "<p>" + Message + "<img src=" + imgURL + "></p> </div>");
var notes = $('#notes').html();
localStorage.setItem('notes', notes);
saveDataToLocalStorage(imgURL);
}
reader.readAsDataURL(pic);
return false;
});
//show content of notes in storage
$('#notes').html(localStorage.getItem('notes'));
return false;
But despite messing around with it for a couple of hours, I'm not getting it to work. Can anyone lend a hand with this?
I'm also concerned about compression. Do I need to use base64 encoding or something in case the image size causes the whole thing to crash?
Just check to see if there is an imaged saved on page load and display it. Then save the image when selected.
$(document).ready(function () {
$("#getPic").on("change", gotPic);
if (localStorage['url']){
$("#image").attr("src", localStorage['url']);
$("#picButt span").text("Change image");
}
});
function gotPic(event) {
var reader = new FileReader();
reader.onload = function(){
$("#image").attr("src", this.result);
localStorage['url'] = this.result;
$("#picButt span").text("Change image");
}
reader.readAsDataURL(event.target.files[0]);
}
https://jsfiddle.net/cq2yrh2z/1/
I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.
<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>
$("#filput").on('change', function () {
var w = $(this).width();
if (w < 500) {
alert("too small");
} else {
alert("big");
}
});
The this referrs to the input not the image. You have too use the HTML5 file API.
You can use this example: How to get the image width from html 5 file API
Code example: copied from: Getting Image Dimensions using Javascript File API
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});