I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.
function previewImage(element) {
var reader = new FileReader();
reader.onload = function (event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
var img = new Image();
img.onload = function () {
alert(this.width + 'x' + this.height);
}
I am implementing these two combine but how can i check the size of image?
FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:
function previewImage(element) {
var reader = new FileReader();
reader.onload = function(event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
//log / access file size in bytes
console.log(element.files[0].size + ' Bytes');
//log / access file size in Mb
console.log(element.files[0].size/1024/1024 + ' MB');
if (element.files[0].size/1024/1024 > 4) {
console.log('file is bigger than 4MB);
}
}
That might be what you want:
var size = files[0].size;
You can check the file size before submitting:
<!doctype HTML>
<html>
<head>
<script>
function checkFileSize() {
var size = document.getElementById("fileSelector").files[0].size;
alert("file size: " + size);
}
</script>
</head>
<body>
<input id="fileSelector" type="file" onchange="checkFileSize()"/>
<input type="submit" />
</body>
</html>
This is working code to get file size. you will get file size in KB.
<input id="file" type="file">
<img id="filerendered" src="">
and in script tag
document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
files = targetn.files;
// FileReader here
if (FileReader && files && files.length) {
var thisReader = new FileReader();
alert("your file size "+ (files[0].size)/1024 + "kb")
thisReader.onload = function () {
document.getElementById("filerendered").src = thisReader.result;
}
thisReader.readAsDataURL(files[0]);
}
// for Not supported case
else {
// not supported
}
}
Related
Using a JS snippet I found here I am able to preview images prior to upload, here is that code...
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 85;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
My issue is despite the filenames of the images being uploaded being like 1-black, 2-red, 3-blue etc when they are previewed they are in a random order, the desired output would be to show them in alphabetical order.
I have been looking at images.sort(); // use sort function of javascript. but can't figure out how to use it!
if I upload 3 items with the file name: png1, png2, png3 Result will
be like this.
alert 1
png1 / base64 string convertion
alert 2
png2 / base64 string convertion
alert 3
png3 / base64 string convertion
I tried this code.
function readFile() {
var input = document.getElementById('gallery-photo-add');
var nameOfFile = "";
for (var i = 0; i < input.files.length; ++i) {
nameOfFile = input.files.item(i).name;
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.addEventListener("load", function (e) {
alert(nameOfFile);
alert(e.target.result);
});
reader.readAsDataURL(this.files[0]);
}
}
}
document.getElementById("gallery-photo-add").addEventListener("change", readFile);
<input type="file" multiple id="gallery-photo-add" style="overflow: auto;">
Try using + operation to display filename and base64 toghther in one alert.
Here is the reference to read more about JS operators
Edit: You want to alert and base64 togther which is not simple straight forward as base64 comes from FileReader API and filename is from input
I have wrapped your base64 and alert in function and also have simplified the JS code your to call the function onchange
Working Demo: https://jsfiddle.net/usmanmunir/hpej8f6o/
Run snippet below to see it working.
function readFile(input) {
//Store file name
var filesName = []
//Get total files
var filesTotal = input.files.length;
for (var i = 0; i < filesTotal; ++i) {
//Store file names
filesName.push(input.files.item(i).name)
var reader = new FileReader();
//Display alert and base64
function displayAlert(i) {
reader.addEventListener("load", function(e) {
alert(filesName[i] + ' Base64 ' + e.target.result);
})
}
reader.readAsDataURL(input.files[i]);
//Display Alerts
displayAlert(i)
}
}
<input type="file" multiple id="gallery-photo-add" onchange="readFile(this)" style="overflow: auto;">
I've been trying to piece together a combination of HTML5 video tag + the FileReader API but I haven't figured out how to get the dimensions of a video that a user is providing from their own computer.
Here is what I am referencing for width/ height:
HTML5 Video Dimensions
<video id="foo" src="foo.mp4"></video>
var vid = document.getElementById("foo");
vid.videoHeight; // returns the intrinsic height of the video
vid.videoWidth; // returns the intrinsic width of the video
But I want to know if it's possible to do this with a file from a user's computer (that they have selected via a normal input html tag).
Thanks!
A bit unclean solution using basic FileReader + Data URL.
<html>
<head>
<style>
div {
margin: 20px;
}
</style>
</head>
<body>
<h1>Get Dimensions</h1>
<div>
<label for="load-file">Load a file:</label>
<input type="file" id="load-file">
</div>
<div>
<button type="button" id="done-button">Get me dimensions</button>
</div>
<script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
<script>
(function ($) {
$('#done-button').on('click', function () {
var file = $('#load-file')[0].files[0];
var reader = new FileReader();
var fileType = file.type;
console.log("type", fileType);
reader.addEventListener("load", function () {
var dataUrl = reader.result;
var videoId = "videoMain";
var $videoEl = $('<video id="' + videoId + '"></video>');
$("body").append($videoEl);
$videoEl.attr('src', dataUrl);
var videoTagRef = $videoEl[0];
videoTagRef.addEventListener('loadedmetadata', function(e){
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
})(jQuery);
</script>
</body>
</html>
Here is a simple and fast solution to get a video's size before upload.
It doesn't require any dependency.
const url = URL.createObjectURL(file);
const $video = document.createElement("video");
$video.src = url;
$video.addEventListener("loadedmetadata", function () {
console.log("width:", this.videoWidth);
console.log("height:", this.videoHeight);
});
const onSelectVideo = (files) => {
const file = files[0];
const url = URL.createObjectURL(file);
let videoId = "videoMain";
const video = document.createElement("video");
const body = document.getElementsByTagName("body");
video.setAttribute("src", url);
video.setAttribute("videoId", videoId);
body[0]?.append(video);
let videoTagRef = document.querySelector("[videoId='videoMain']");
videoTagRef.addEventListener("loadedmetadata", function (e) {
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});}
Hi i'm using the following code to get the upload image using File Reader API:
<script type="text/javascript">
var loadImageFile = (function () {
if (window.FileReader) {
var oPreviewImg = null, oFReader = new window.FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function (oFREvent) {
/*get image*/
var _img = oFREvent.target.result;
console.log(oFREvent.target);
/*add img to hidden input text*/
localStorage.photo = _img;
oPreviewImg.src = oFREvent.target.result;
};
return function () {
var aFiles = document.getElementById("imageInput").files;
if (aFiles.length === 0) { return; }
if (!rFilter.test(aFiles[0].type)) {
notify("You must select a valid image file!",3400,false); return;
}
oFReader.readAsDataURL(aFiles[0]);
}
}
})();
</script>
<form name="uploadForm">
<p><input id="imageInput" type="file" name="myPhoto" onchange="loadImageFile();" /><br />
<input type="submit" value="Send" /></p>
<input type="hidden" id="photo_1_hidden" name="photo_1"/>
</form>
it works great and it returns the base64 data of the image.
now i would like to get also the image file size and the image width and height.
Is it possible?
I tryed to log in console the file but i can't find what i'm searching for.
Any help appriciated thanks so much!
Something like this?
var oPreviewImg = new Image();
oPreviewImg.onload = function(){
console.log(this.size);
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
};
oPreviewImg.onerror = function(){
alert("'" + this.name + "' failed to load.");
return true;
}
oPreviewImg.src = "//placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150";
var xhr = new XMLHttpRequest();
xhr.open('HEAD', oPreviewImg.src, true);
xhr.onreadystatechange = function() {
console.log('this', this);
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);
Live version
Update Live version replaced with Fiddle, however, due to cross site scripting concerns, the size is no longer being retrieved effectively.
const reader = new FileReader()
reader.onload = (theFile) => {
const image = new Image()
image.src = theFile.target.result
image.onload = () => {
console.log('image width ===== ' + image.width + 'Image height
===== ' + image.height)
}
}
reader.readAsDataURL(item)
I don't believe that JS is going to be capable of getting that data without first rendering the image to the viewport. That is to say, I am unfamiliar of any method that would do what you ask in the JavaScript, or JQuery libraries. Your best bet for getting data like that is going to be rendering the image to the page in a preview capacity or using a more powerful language like PHP and using an Ajax request to get the data you're looking for.
I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});