Javascript image size check (bytes) - javascript

I'm having trouble getting my code to work. The first section of my javascript does not work. The last part works but inserts the image after the message.
Could my code be in conflict with my other javascript file? That does not explain why the second part works and add the image anyways though?
My javascript is in the same file as my HTML because otherwise the onload function wouldn't work.
<script>
window.onload = function(){
var uploadField = document.getElementById("frontImages");
uploadField.onchange = function() {
if(this.files[0].size > 200){
alert("File is too big!");
this.value = "";
};
};
}
window.onload = function() {
var uploadField = document.getElementById("itemImages");
uploadField.onchange = function() {
if(this.files[0].size > 200){
alert("File is too big!");
this.files = "";
};
};
}
</script>
My HTML:
<div class="row">
<div class="col-md-6">
<label>Front Image:</label>
<input type="file" name="frontImage[]" id="frontImages" class="form-control uploadButton" required="true">
<div id="previewFront" class="previewImage">
<img id="previewFrontImage" style="display: none;" src="#"/>
</div>
<label>Please upload a jpg, jpeg, gif or a png file. (MAX 2MB)</label>
</div>
<div class="col-md-6">
<label>Item Image(s):</label>
<input type="file" name="itemImages[]" id="itemImages" class="form-control uploadButton" multiple="true" required="true">
<div id="previewItemImages" class="previewItemImage"></div>
<label>Please upload a jpg, jpeg, gif or a png file. (MAX 2MB)</label>
</div>
</div>

You should use
window.addEventListener("load", function(event) {
//your code
});
instead of window.onload, because when you set window.onload second time you overwrite your previously setted function. window.addEventListener allow you to add more than one event.
Documentation: https://developer.mozilla.org/en-US/docs/Web/Events/load

Related

Can't get image to display via jQuery when it's being uploaded

Right now I have a url that displays an image when it's loaded. However, there will be an option for this image to be replaced via a form input. I would like the uploaded image to be displayed as soon as it's uploaded so it can be evaluated by the user.
I'm trying to accomplish this via jQuery, but I can't get it to work.
Here's my code:
HTML:
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<img src="..\{{ workshop_info[4] }}" id="output">
</div>
JQuery:
<script>
$(document).ready(function() {
$("#Image").change(function(e){
$("#output").attr("src", e.target.files[0]);
});
});
</script>
You can do this by using FileReader functionality.
I have recreated your example which displays an image when it's loaded
Once i upload my own image by clicking choose file and selected the file. That file will be getting previewed after selection with that image load_images div i created.
As soon as the file is selected i am replace the src of your existing image to the new src which come from readAsDataURL
You can read more about FileReader here in detail.
Working Demo: https://jsfiddle.net/usmanmunir/w5cbgLsk/
Run snippet below to see it working.
$(function() {
//Preview image function
var previewImage = function(image) {
if (image.files) {
//Check all images
var filesAmount = image.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
//Replace images on form upload selected image
$('#output').attr('src', event.target.result)
}
reader.readAsDataURL(image.files[i]);
}
}
};
//Select image and call imagePreview function
$('#Image').on('change', function() {
previewImage(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<div class="load_images">
<img src="http://mandarinazul.co/images/mandarinas.png" id="output">
</div>
</div>
<img src="../yourimage/path/image.jpeg" onclick="previmg()" id="displayimage" />
<input type="file" class="form-control" onchange="selectedimg(this)" id="selectphoto" style="display: none" name="photo">
</div>
function previmg(){
document.querySelector('#selectphoto').click();
}
function selectedimg(e){
if(e.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.querySelector('#displayimage').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]);
}}
OR you can try this too,
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="image has to be load">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}}
try this, both will work charm if any doubt feel free to ask.:-)

HTML multiple fileread

HTML Code:
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
jQuery Code:
for(var i = 1; i <= 4; i++){
if($("#img"+i).val() != ''){
file = document.getElementById('img' + i).files[0];
fileread(file);
}
}
function fileread(file){
var result = '';
reader = new FileReader();
reader.onload = function(){
result = reader.result;
//return result;
localStorage.setItem("lostimage1", result);
}
reader.readAsDataURL(file);
}
I want to read multiple files when user click on submit button. but it not working. How can I resolve this error? please help me.
Using Jquery and each() method I suggest this:
var checkValue;
var valueArray=[];
$('#button').on('click',function(){
$('input').each(function(){
checkValue=$(this).val();
if(checkValue===''){
return;
}
valueArray.push(checkValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
<button id="button">Click Me</button>
Attach click event to <input type="submit">, call event.preventDefault() to prevent <form> submission, use .each() to iterate <input type="file"> elements, pass this.files[0] to readfile function.
Adjust within FileReader load handler to not overwrite same key at localStorage.
FileReader throws an error if a Blob or File object is not passed as parameter to .readAsDataURL(), for example, ifis clicked andfilereadis called in loop and one ofelements.filesproperty doe not containFileobject inFileList. Check if element.fileshas.lengthgreater than0before callingfilereadreferencing the.files[0]property of the current` element.
$(function() {
function fileread(file, id) {
var reader = new FileReader();
reader.onload = function() {
localStorage.setItem("lostimage" + id, reader.result);
}
reader.readAsDataURL(file);
}
$("input[type=submit]").on("click", function(e) {
e.preventDefault();
$(":file[id^=img]").each(function() {
if (this.files.length) fileread(this.files[0], this.id.replace(/\D/g, ""))
})
});
});
plnkr http://plnkr.co/edit/1Sec8uWlK2pbXMTlfpCj?p=preview

Restrict image upload size [duplicate]

I have an html select option for uploading images.
<div class="row smallMargin">
<div class="col-sm-6">
Attach Image
</div>
<div class="col-sm-6">
<input type="file" ng-model="image" accept="image/*">
</div>
</div>
How can I restrict the user from uploading images which are larger than 2MB?
This example should give you an idea of how to do it:
HTML
<form class="upload-form">
<input class="upload-file" data-max-size="2048" type="file" >
<input type=submit>
</form>
JS
$(function(){
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
$('.upload-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more than ' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct - '+fileSize+' bytes');
}
}else{
alert('Please select the file to upload');
return false;
}
});
});

javascript accept only image not working

In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?
https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />
You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}

how to browse multiple image or file in jquery?

I want to show multiple files or images after browse from system not uploaded on server can we show this using jquery?
I goggled it and find there is way to show and upload on server:
http://www.dropzonejs.com/
But. I only want to show images or file in this there is drag and drop functionality also present can we use this plugin.
But, when I use this plugin in fiddle it show only attached file name not display image why?
Here is fiddle:
http://jsfiddle.net/my50a3uh/1/
<form id="my-awesome-dropzone" action="/target" class="dropzone"></form>
<input type="file" name="file" />
I hope it may be useful for you.It is running well.
Live Working Demo
HTML Code:
<form enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
JS Code
function fileSelect(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.target.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 90px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
document.getElementById('filesToUpload').addEventListener('change', fileSelect, false);

Categories