How to upload multiple PDF files using jQuery? - javascript

I'm trying to upload multiple pdf files using php, but the following code is allowing to upload only img, png....I have added application/pdf but only one PDF file is being uploaded, not multiple. I want to upload multiple PDF files same as this code is uploading accepted files, selecting one by one and all at once.
Can you please help me to upload multiple pdf files and upload in sql?
Thank you.
<div>
<label style="font-size: 14px;">
<span style='color:navy;font-weight:bold'>Attachment Instructions :</span>
</label>
<ul>
<li>
Allowed only files with extension (jpg, png, gif)
</li>
<li>
Maximum number of allowed files 10 with 300 KB for each
</li>
<li>
you can select files from different folders
</li>
</ul>
<!--To give the control a modern look, I have applied a stylesheet in the parent span.-->
<span class="btn btn-success fileinput-button">
<span>Select Attachment</span>
<input type="file" name="files[]" id="files" multiple accept="image/jpeg, image/png, image/gif,"><br />
</span>
<output id="Filelist"></output>
</div>
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
//un ordered list to keep attachments thumbnails
var ul = document.createElement("ul");
ul.className = "thumb-Images";
ul.id = "imgList";
function init() {
//add javascript handlers for the file upload event
document
.querySelector("#files")
.addEventListener("change", handleFileSelect, false);
}
//the handler for file upload event
function handleFileSelect(e) {
//to make sure the user select file/files
if (!e.target.files) return;
//To obtaine a File reference
var files = e.target.files;
// Loop through the FileList and then to render image files as thumbnails.
for (var i = 0, f; (f = files[i]); i++) {
//instantiate a FileReader object to read its contents into memory
var fileReader = new FileReader();
// Closure to capture the file information and apply validation.
fileReader.onload = (function(readerEvt) {
return function(e) {
//Apply the validation rules for attachments upload
ApplyFileValidationRules(readerEvt);
//Render attachments thumbnails.
RenderThumbnail(e, readerEvt);
//Fill the array of attachment
FillAttachmentArray(e, readerEvt);
};
})(f);
// Read in the image file as a data URL.
// readAsDataURL: The result property will contain the file/blob's data encoded as a data URL.
// More info about Data URI scheme https://en.wikipedia.org/wiki/Data_URI_scheme
fileReader.readAsDataURL(f);
}
document
.getElementById("files")
.addEventListener("change", handleFileSelect, false);
}
//To remove attachment once user click on x button
jQuery(function($) {
$("div").on("click", ".img-wrap .close", function() {
var id = $(this)
.closest(".img-wrap")
.find("img")
.data("id");
//to remove the deleted item from array
var elementPos = AttachmentArray.map(function(x) {
return x.FileName;
}).indexOf(id);
if (elementPos !== -1) {
AttachmentArray.splice(elementPos, 1);
}
//to remove image tag
$(this)
.parent()
.find("img")
.not()
.remove();
//to remove div tag that contain the image
$(this)
.parent()
.find("div")
.not()
.remove();
//to remove div tag that contain caption name
$(this)
.parent()
.parent()
.find("div")
.not()
.remove();
//to remove li tag
var lis = document.querySelectorAll("#imgList li");
for (var i = 0; (li = lis[i]); i++) {
if (li.innerHTML == "") {
li.parentNode.removeChild(li);
}
}
});
});
//Apply the validation rules for attachments upload
function ApplyFileValidationRules(readerEvt) {
//To check file type according to upload conditions
if (CheckFileType(readerEvt.type) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, You can only upload jpg/png/gif files"
);
e.preventDefault();
return;
}
//To check file Size according to upload conditions
if (CheckFileSize(readerEvt.size) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB"
);
e.preventDefault();
return;
}
//To check files count according to upload conditions
if (CheckFilesCount(AttachmentArray) == false) {
if (!filesCounterAlertStatus) {
filesCounterAlertStatus = true;
alert(
"You have added more than 10 files. According to upload conditions you can upload 10 files maximum"
);
}
e.preventDefault();
return;
}
}
//To check file type according to upload conditions
function CheckFileType(fileType) {
if (fileType == "image/jpeg") {
return true;
} else if (fileType == "image/png") {
return true;
} else if (fileType == "image/gif") {
return true;
} else {
return false;
}
return true;
}
//To check file Size according to upload conditions
function CheckFileSize(fileSize) {
if (fileSize < 300000) {
return true;
} else {
return false;
}
return true;
}
//To check files count according to upload conditions
function CheckFilesCount(AttachmentArray) {
//Since AttachmentArray.length return the next available index in the array,
//I have used the loop to get the real length
var len = 0;
for (var i = 0; i < AttachmentArray.length; i++) {
if (AttachmentArray[i] !== undefined) {
len++;
}
}
//To check the length does not exceed 10 files maximum
if (len > 9) {
return false;
} else {
return true;
}
}
//Render attachments thumbnails.
function RenderThumbnail(e, readerEvt) {
var li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = [
'<div class="img-wrap"> <span class="close">×</span>' +
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(readerEvt.name),
'" data-id="',
readerEvt.name,
'"/>' + "</div>"
].join("");
var div = document.createElement("div");
div.className = "FileNameCaptionStyle";
li.appendChild(div);
div.innerHTML = [readerEvt.name].join("");
document.getElementById("Filelist").insertBefore(ul, null);
}
//Fill the array of attachment
function FillAttachmentArray(e, readerEvt) {
AttachmentArray[arrCounter] = {
AttachmentType: 1,
ObjectType: 1,
FileName: readerEvt.name,
FileDescription: "Attachment",
NoteText: "",
MimeType: readerEvt.type,
Content: e.target.result.split("base64,")[1],
FileSizeInBytes: readerEvt.size
};
arrCounter = arrCounter + 1;
}

Related

How do I delete a single file from input type file multiple?

I am following this documents https://www.webtricks.cf/2022/08/preview-an-image-before-it-is-uploaded.html for multiple image uploader and i am trying to delete one specific image or file from input mulitple file but unfortunatly preview image is deleting on client side but not deleting from input file please help me how can I resolve that thank u ?
html view
<input type="file" multiple />
javascript
/** Variables */
let files = [],
dragArea = document.querySelector('.drag-area'),
input = document.querySelector('.drag-area input'),
button = document.querySelector('.card button');
select = document.querySelector('.drag-area .select');
container = document.querySelector('.container');
/** CLICK LISTENER */
select.addEventListener('click', () => input.click());;
/* INPUT CHANGE EVENT */
input.addEventListener('change', () => {
let file = input.files;
// if user select more than 1 image or no image
if (file.length > 1 || file.length == 0) return;
files.push(file[0]);
input.files = null;
showImages();
})
/* SHOW IMAGES */
function showImages() {
let images = files.reduce(function(prev, file, index) {
return (prev += `<div class="image">
<img src="${URL.createObjectURL(file)}" alt="image">
<span onclick="delImage(${index})">×</span>
</div>`);
container.innerHTML = images;
}, "");
}
input.addEventListener('change', () => {
let file = input.files;
// if user select more than 1 image or no image
if (file.length > 1 || file.length == 0) return;
files.push(file[0]);
input.files = null;
container.innerHTML = `<div class="image">
<img src="${URL.createObjectURL(file[0])}" alt="image">
<span onclick="delImage(0)">×</span>
</div>`;
})
/* DELETE IMAGE */
function delImage(index) {
files.splice(index, 1);
showImages();
}

How to put a multiple file selection into an array to output

I have a file upload application which once a file has been selected status will appear saying the name of the file. What I am having an issue with is adjusting the case where there are more than one files being uploaded.
Originally, a count would be given - if you upload three files, '3' would appear. I am attempting to adjust this so that the three file names are displayed. I took the code getting the single file name to show fileName = e.target.value.split('\\').pop(); and tried adding it to the condition is more than one:
if (this.files && this.files.length > 1) {
//fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
//fileName = e.target.value.split('\\').pop();
fileName = e.target.value.split('\\').pop();
console.log('Here is it ' + fileName);
//$('#fileName').html(fileName);
}
What I get is a single file name outputted. I can't figure out how to get the file name list in an array to output.
Does anyone see what I need to adjust?
var inputs = document.querySelectorAll('.inputfile');
Array.prototype.forEach.call(inputs, function(input) {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
if (this.files && this.files.length > 1) {
//fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
//fileName = e.target.value.split('\\').pop();
fileName = e.target.value.split('\\').pop();
console.log('Here is it ' + fileName);
//$('#fileName').html(fileName);
} else {
fileName = e.target.value.split('\\').pop();
console.log("I am running");
}
if (fileName) {
//label.querySelector('span').innerHTML = fileName;
//label.querySelector('span').innerHTML = fileName;
$('#fileName').html(fileName);
$('#fileStatus').text('File attached!');
} else {
label.innerHTML = labelVal;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple>
<label for="uploadedFileTest" id="uploadFileTest"><img class="total-center" src=""></label>
<p id="fileStatus"></p>
<p id="fileName"></p>

how to retrieve data length in console log

how to get data length inside Files ? i need data length to make alert maximize file
I want to limit the maximum upload of image files by adding alerts to the following code
the alert is alert("You Have Reached The MAXIMUM Upload Limit"); so when I add one by one upload image to the specified limit, an alert will appear
i want to get data length after click upload one by one but the data length is always 0 why ?
html
<div class="files col-sm-4" id="files1">
<input type="file" name="files1" id="imageten" multiple />
<br />Selected files:
<ol class="fileList"></ol>
</div>
script
$.fn.fileUploader = function (filesToUpload) {
this.closest(".files").change(function (evt) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<i class=\"fa fa-times fa-close removeFile\" href=\"#\" data-fileid=\"" + i + "\"></i>";
output.push("<li><strong>", escape(f.name), "</strong> ", removeLink, " </li> ");
}
$(this).children(".fileList").append(output.join(""));
console.log(evt.target.files);
});
};
var filesToUpload = [];
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
filesToUpload.splice(i, 1);
console.log(filesToUpload);
}
}
$(this).parent().remove();
});
There is no variable named data in your code. I did not understood where you are returning 0. But, if my guess is correct, add this line inside $(document).on("click",".removeFile", function(e){
$(this).children(".fileList").append(output.join(""));
console.log(evt.target.files);
alert(evt.target.files.length); // add this line
$("#fileinput")[0].files.length will give the number of files.
if($("#fileinput")[0].files.length > 2) {
alert("You can select only 2 files");
}
Let me know if this is helpful.
How to limit the maximum files chosen when using multiple file input - There are already questions like this on stackoverflow.

Send image dropped into div with other elements of a common Post [duplicate]

This question already has an answer here:
How to set file input value when dropping file on page? [duplicate]
(1 answer)
Closed 4 years ago.
I have a small HTML5 form where the user drops an image file, sees the preview, gets to know the dimensions of the image, fills an input element, and hits the button "Send" to dispatch it all (image and input text) through a POST request.
Problem is, the image data is not being sent together with the input data, even if the div and img elements have a name tag assigned to them. How can I accomplish that using the usual POST process?
Here is my code.
function removeDragData(e) {
if (e.dataTransfer.items) { // Use DataTransferItemList interface to remove the drag data
e.dataTransfer.items.clear();
} else { // Use DataTransfer interface to remove the drag data
e.dataTransfer.clearData();
}
}
function formatBytes(a,b) {
if (0 == a)
return '0 Bytes';
var c = 1024,
d = b || 2,
e = ['Bytes','KB','MB','GB','TB','PB','EB','ZB','YB'],
f = Math.floor(Math.log(a)/Math.log(c));
return parseFloat((a/Math.pow(c,f)).toFixed(d))+' '+e[f];
}
function getDim(img,tam) {
var infoW = img.naturalWidth;
var infoH = img.naturalHeight;
var info = document.getElementById('addDadoInfo');
info.innerHTML = 'Tamanho: ' + infoW + ' x ' + infoH + ' pixels (' + formatBytes(tam) + ')';
}
function drop(e,who) {
e.preventDefault(); // Prevent default behavior (Prevent file from being opened)
var i;
if (e.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s)
for (i=0; i<e.dataTransfer.items.length; i++) {
if (e.dataTransfer.items[i].kind === 'file') { // If dropped items aren't files, reject them
var file = e.dataTransfer.items[i].getAsFile();
if (file.type.indexOf('image/') == 0 && file.size <= 2*1024*1024) {
// Process only the first image up to 2 MB
var img = document.createElement('img');
var tam = file.size;
img.file = file;
img.name = 'imgDImg';
img.style.maxWidth = '400px';
img.style.maxHeight = '300px';
while (who.firstChild) {
who.removeChild(who.firstChild); // removes the <p> element
}
who.appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(ev) {
aImg.src = ev.target.result;
setTimeout(getDim,500,aImg,tam);
};
})(img);
reader.readAsDataURL(file);
break;
//console.log('.A. file[' + i + '] = ' + file.name + '|' + file.type + '|' + file.size);
}
}
}
} else { // Use DataTransfer interface to access the file(s)
for (i=0; i<e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
console.log('.B. file[' + i + '] = ' + file.name + '|' + file.type + '|' + file.size);
}
}
removeDragData(e); // Pass event to removeDragData for cleanup
}
function dragOver(e) {
e.preventDefault(); // Prevent default behavior (Prevent file from being opened)
}
.addDado {
background-color:#DDD;
width:400px;
height:300px;
text-align:center;
}
<form id='frmAddDado' autocomplete='on' method='post' action='index.php'>
<div id='addDado1' name='addDado1' class='addDado' ondrop='drop(event,this)' ondragover='dragOver(event)'>
<p>Drop image here.</p>
</div>
<div id='addDadoInfo'>(No data selected.)</div>
<br>
<label for='txaDRef'>Reference</label><br>
<textarea id='txaDRef' name='txaDRef' cols=80 rows=5></textarea><br>
<br>
<input id='btnAddDado' type='submit' value='Add' disabled />
</form>
Well, this answer helped me to get it partially done, converting the image into base64 and attaching this to a hidden input. However, it's only 100% ok for PNG images. If the user tries to upload a JPG, there's no way it seems I can save the file as-is, i.e. without losing quality or increasing the file size.
So, I'm still looking for a better way to have both: thumbnail, dimensions and file size displayed and perfect file transfer.
EDIT
Digging more, I've found this answer, which does exactly what I needed!
A few modifications to the code above:
// in <form id='frmAddDado'>
<input id='fileIMG' name='fileIMG' type='file' style='display:none' />
// in function drop(e,who)
document.getElementById('fileIMG').files = e.dataTransfer.files;

How To Remove selected file in Javascript/Jquery

I have a form that allows users to upload multiple images. Users has an option to remove Images one by one if they don't want to upload that particular image.
Now, How to remove the value from the file type of the one that they removed (e.g. didn't want to upload)?
I have tried using ($('input').val("")) but it works only for single image not for multiple images. If I used this for multiple image then all uploaded images value become empty instead of that particular image that user want to remove.. Below is my Code:-
HTML
<input type="file" id="files2" name="cert_img" multiple>
<output id="list2"></output>
Javascript
var count2=0;
function handleFileSelect2(evt) {
var $fileUpload = $("input#files2[type='file']");
count2=count2+parseInt($fileUpload.get(0).files.length);
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" id="image_X" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('list2').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
$('#files2').change(function(evt){
handleFileSelect2(evt);
});
$('#list2').on('click', '.remove_img_preview',function () {
$(this).parent('span').remove();
//$('input').val("");
});
Thanks in advance..
According to this question you can't change FileList content because it is readonly.
But if you want to remove a file of FileList, you can create a new object and set to it files that you want to upload. Then use created object to upload files. Run my example and select multiple files. Then click on any file that you want to delete. After delete files, see browser console.
var files;
$("#files").on("change", function(e){
files = $("#files")[0].files;
$.each(files, function(index, value){
$("ol").append("<li data-index='"+index+"'>"+ value.name +"</li>");
});
});
$(document).on("click", "li", function(){
var newFiles = {};
var index = $(this).index();
$("li:nth-child(" + (index + 1) + ")").remove();
$("li").each(function(index, element){
var dataIndex = $(element).attr("data-index");
newFiles[index] = files[dataIndex];
});
console.log(newFiles);
});
li:hover {
color: red;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="files" multiple>
<ol></ol>

Categories