I have the code given below it is counting the files when i select the files and alert that you cannot select more than etc...
Limit is 4 and when i select 6 it says cannot select more than 4. But when i select 4 it adds and show thumb anad again on selecting one or 4 it adds again the new 4 or whatever files, so user can upload unlimited files.
How can i catch that selected files and restrict them.
<div class="m-form__group form-group row">
<label for="exampleInputEmail1" class="col-form-label col-lg-3 col-sm-12">
Select Image
</label>
<div class="col-lg-9 col-md-9 col-sm-12">
<div class="col-lg-12 col-md-9 col-sm-12" id="thumb-output">
<input id="files" class="" type="file" name="file[]" multiple>
</div>
</div>
</div>
$(document).ready(function() {
$('input[type=file]').on('dragenter', function() {
$('div').addClass('dragover');
});
$('input[type=file]').on('dragleave', function() {
$('div').removeClass('dragover');
});
if (window.File && window.FileList && window.FileReader) {
var numFiles = $('input[type=file]')[0].files.length;
$("#files").on("change", function(e) {
var files = e.target.files, filesLength = files.length;
if(files.length > 4){
alert("you can select max 4 files.");
}else{
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
You can use a global variable to track how many files have been added.
var fileAdded = 0;
...
if(fileAdded + files.length > 4){
alert("you can select max 4 files.");
} else {
fileAdded = fileAdded + files.length;
for (var i = 0; i < files.length; i++) {
...
}
}
Also, please remember to decrease fileAdded when the user delete a file.
Here is an example:
var fileDict = new Object();
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
var numFiles = $('input[type=file]')[0].files.length;
$("#files").on("change", function(e) {
var files = e.target.files, filesLength = files.length;
if(Object.keys(fileDict).length + files.length > 4){
alert("you can select max 4 files.");
}else{
for (var i = 0; i < filesLength; i++) {
var f = files[i];
fileDict[f.name] = f;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
$("<div class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + f.name + "\"/>" +
"<br/><span class=\"remove\" data-name=\""+f.name+"\">Remove</span>" +
"</div>").insertAfter("hr");
});
fileReader.readAsDataURL(f);
}
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
$(document).on('click', '.remove', function(){
delete fileDict[$(this).data("name")];
$(this).parent(".pip").remove();
});
var upload = function() {
let formData = new FormData();
var i = 0;
Object.keys(fileDict).forEach(item => {
formData.append("file" + i, fileDict[item]);
i += 1;
});
$.ajax({
type: 'post',
url: '/upload.php',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: formData ,
success: function(data) {
alert(data);
}
});
}
img {
max-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="files" class="" type="file" name="file[]" multiple>
<hr>
<input type="button" value="Upload" onclick="upload()">
I am not sure which language you are using for backend. I use PHP here:
<?php
if (count($_FILES) > 4) {
echo "you can select max 4 files.";
} else {
foreach ($_FILES as $file_id => $file) {
if ($file['error'] > 0) {
echo 'Error: ' . $file['error'] . '<br>';
} else {
move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
echo 'uploads/' . $file['name'] . '<br>';
}
}
}
Related
I have a JQuery multi-file upload solution that requires restriction on file format and size.
Here's the JSFIDDLE, and the JS code follows below:
$(document).ready(function() {
if (window.File && window.FileList &&
window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
The desired outcome is to allow me to set both the file type and size that can be easily changed.
Thanks for any help!
You can set a condition right after you declare a value to your var f
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
You can also console.log(f); for more properties
Here is my version of your function:
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
else{
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
You can check the size property of the file and the type property of the file.
var maxSize = 20000;//maximum size for the file
var acceptedTypes = ["image/png", "image/jpg"];//accepted image types
if(f.size>maxSize){
//file is too big
}
if(acceptedTypes.indexOf(f.type)<0){
//file type is not accepted
}
JSFiddle: https://jsfiddle.net/ordmsw8p/
My project has multiple image upload space. I choose 4 pictures. I have selected one of the pictures removed when the file is not selected what is the reason?
<div class="aupload">
<img src="{{ url_for('static', filename='admin/images/upload.png') }}" class="uploadImage" alt="">
<input type="file" id="files" name="files[]" multiple />
</div>
<button type="submit" class="btn form-control btn-default">Kaydet</button>
<script>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div class=\"preview\">" +
"</span><img class=\"uploadImg\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<span class=\"remove\"><i class=\"fa fa-times\"></i>" +
"</div>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".preview").remove();
$('#files').val("");
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
What I want to do is: clicking the remove button will remove the uploaded photo and reduce the number of files selected. I'd appreciate it if you could help.
I have a need to get the JSFIDDLE DEMO to keep the ability to upload multiple files, but instead displaying the preview, I need to display the multiple file names only.
Here's the JSFIDDLE JS used to upload the files:
$(document).ready(function() {
if (window.File && window.FileList &&
window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File
API")
}
});
In addition, I need to be able to upload only the following file types: .jpg, .png, .pdf, .xlsx and .docx.
Thank for any help!
If you just want to show the file names you don't need to use the img tag. You can change the code as following.
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
$("<span class=\"pip\">" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i>"+ f.name + "</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".pip").remove();
});
}
});
} else {
alert("Your browser doesn't support to File API")
}
And for the 2nd question, you can define the accepted types in your html as
<div class="file-loading">
<input type="file" id="files" name="files[]" multiple accept=".jpg,.png,.pdf,.xlsx,.docx"/>
</div>
I'm using a input type file multiple to update some pictures. Before upload, the page shows a miniature of each picture. I would like to do a remove link to each picture, and when the user clicks, the picture disapear and the file is removed from input.
I try to use this code below:
HTML:
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" />
<div id="midiaDigital"></div>
Javascript:
$(document).ready(function() {
$("#midiasUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#midiaDigital");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$(image_holder).append('<div class="form-group row">' +
'<div>' +
'<div class="col-md-6">' +
'<img src="' + e.target.result + '" class="thumb-image img-responsive">' +
'<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' +
'Remover' + //add input box
'</div>' +
'</div>' +
'</div>');
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("O browser não suporta upload de arquivos.");
}
} else {
alert("Formato de arquivo inválido");
}
});
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
})
});
Using this code, the "preview" pictures appear with the "remove" link. When I click in the "remove", the preview picture are deleted, but the file continues selected. What should I do?
You can do it simply via jQuery in one line: $('#midiasUpload').val('');. It resets input value. Here is the snippet:
function select(el) {
img = el;
}
var img;
var input;
$(document).ready(function() {
$("#midiasUpload").on('change', function() {
var countFiles = $(this)[0].files.length;
input = $(this)[0];
console.log('Input value after upload: ', input.value)
var imgPath = input.value;
img = imgPath;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#midiaDigital");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$(image_holder).append('<div class="form-group row">' +
'<div>' +
'<div class="col-md-6">' +
'<img src="' + e.target.result + '" class="thumb-image img-responsive" onclick="select($(this))">' +
'<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' +
'Remover' + //add input box
'</div>' +
'</div>' +
'</div>');
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("O browser não suporta upload de arquivos.");
}
} else {
alert("Formato de arquivo inválido");
}
});
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
img.val = '';
input.value = null;
console.log('Input value after remove: ', input.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" />
<div id="midiaDigital" style="margin-bottom: 100px;"></div>
Please change this code inside $(image_holder).append( function
'Remover' + //add input box
This code works after clicking on remove_field1
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
var deletedId=$(this).prop("data-id");
var names = [];
for (var i = 0; i < $("#midiasUpload").get(0).files.length; ++i) {
if(deletedId==i){}else{ names.push($("#midiasUpload").get(0).files[i].name); }
}
$("#midiasUpload").val(names);
});
I wanted to upload some array of images through JavaScript. I tried the below code:
<script type="text/javascript">
var count =0;
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
count++;
for (var i = 0; i < count; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"removeImg\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".removeImg").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>
But somewhere, when I click the submit button on my form, it sends me only array of one file, which is the last updated file. I wanted array of it..so that I can process that data later.
Please help me out.
i have tested your code it's working fine you just need to replace count variable in for loop with the filesLength variable then you will get all the images not last one that you were getting before!! below is the corrected code. do run the code it will work for you!in upload.php when write you will get number of images you have selected!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
var count =0;
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
console.log(filesLength);
count++;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"removeImg\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".removeImg").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action="upload.php">
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>
<input type="submit" name="submit" value="Submit">
</form>
<form id="imageform" method="post" enctype="multipart/form-data">
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>
<input type="submit" name="submit" value="Submit">
</form>