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;
}
});
});
Related
I tried the code below to get the names of all the images I selected, but when 'alert' I only got 1 name out of the many names I chose. I want all the names of the photos I have selected to be saved in an array
----------------js code-------
$('input[type=file]')[0].files[0].name;
------------html-------------------
<div class="form-group">
<label for="file">Chọn file Ảnh</label>
<input class="form-control" id="file" type="file" name="image[]" multiple="multiple"/>
<input type="submit" value="upload" />
</div>
var images = $('input[type=file]')[0].files;
let imageNames = [];
if(images && images.length) {
imageNames = images.map(image => image.name);
}
console.log('All Images', imageNames);
You can try above solution...
You are using only first image from the array, that's why you are getting only one/first image every time.
welcome to SO. you may need to update the question/description as its vague. here is a small snippet to print all the attriutes of uploaded files as you requested.
function printFiles() {
let dt = $('input[type=file]')[0].files;
for (let i = 0; i < dt.length; i++) {
console.log('file Name: ' + dt[i].name + ', file size: ' + dt[i].size + ', file type: ' + dt[i].type + ', last Modified: ' + dt[i].lastModified +
', last ModifiedDate: ' + dt[i].lastModifiedDate);
console.log('-----------------------------------------');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="file">Chọn file Ảnh</label>
<input class="form-control" id="file" type="file" name="image[]" multiple="multiple" />
<input type="submit" value="upload" onclick="printFiles()" />
</div>
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
i/m doing delete image when the client upload multiple image and preview that image. here is my html
<div class="form-group">
<input id="image" class="" name="image[]" type="file" multiple />
<div class="preview clearfix">
</div>
<div class="upload-img">
<label for="image">
<u>Upload</u>
</label>
</div>
</div>
and here is my JS to upload image and preview images
$("#image").change(function(){
var total_file = document.getElementById('image').files.length;
for(var i = 0; i < total_file ; i++){
var html =
"<div class='img pull-left'>"
+"<img class='preview-img' data-id='"+i+"' id='preview-img-"+i+"' src='"+URL.createObjectURL(event.target.files[i])+"'>"
+"<img class='delete-img' image-id='#preview-img-"+i+"' src='{{ url('/media/error.svg')}}'>"
+'</div>';
$('.preview').append(html);
};
});
$(document).on('click', '.delete-img', function() {
var img = $(this).attr('image-id');
var id_img = $(img).attr('data-id');
var total_files = document.getElementById('image').files;
$(this).closest('.img').remove();
delete total_files[id_img];
});
my problem is delete image in UI but do not delete element image. I want to delete both DOM HTML and file exist in
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='';
}
}
}
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);