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

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>

Related

How to upload multiple PDF files using jQuery?

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;
}

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 fire cancel on open dialog file input on jquery

Hi all i have code for multiple upload image, but i want only one image per upload. so I create the input file every time I clicked the upload button with the dynamic id. however I have problems checking whether the user chooses the file to upload or press the cancel button. because if the user pressed the cancel button I want to delete the input file I have created. for full sourcenya as below:
$(document).ready(function () {
$("#btnimg").click(function () {
//check input file id number
var counter = $("input[id^='upload']").length;
//add input file every btnimg clicked
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
$("#result").append(html);
//trigger to dialog open file
var upload = $('#upload_' + counter);
upload.trigger('click');
upload.on('change', function () {
console.log('change fire...');
var inputFiles = this.files;
var inputFile = inputFiles[0];
var reader = new FileReader();
reader.onload = function (evt) {
var imghtml = "<img id='img_upload_" + counter + "' src='" + evt.target.result + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
};
reader.onerror = function (event) {
alert("something: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
//if file not selected or user press button cancel on open dialog
//upload.remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
</body>
thank you in advance,
You can check the .length of <input type="file"> element .files property to determine if a file is selected by user
That all sounds like an xy-problem to me.
I have not (yet) got a response from you about the why you want to do it, so I will base my answer on two probable situations:
If you want to keep track of the selected Files, in order to be able to do anything with them later (e.g send them through AJAX), then use a single <input>.
At every change event, you will store the new File in an Array, from where you will also be able to do something with later on:
(function() {
// this Array will hold our files, should be accessible to the final function 'doSomething'
var savedFiles = [];
var counter = 0;
var upload = $('#upload');
upload.on('change', onuploadchange);
$("#btnimg").click(function routeClick() {
upload.trigger('click');
});
$('#endbtn').click(function doSomething() {
console.log(savedFiles);
});
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
if (!inputFile) { return; } // no File ? return
savedFiles.push(inputFile); // save this File
// don't use a FileReader here, useless and counter-productive
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
$('#endbtn').removeAttr('disabled');
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
<!-- A single input to save them all-->
<input type='file' id='upload' style='display:none;' />
</div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
<button id="endbtn" disabled>do something with saved files</button>
If, for an obscure reason, you absolutely need to keep all the filled <input> elements in your document, then create a new one only if the last one is itself filled.
$(document).ready(function() {
$("#btnimg").click(function() {
// grab previous ones
var inputs = $("input[id^='upload']");
// get the last one we created
var last = inputs.last();
var counter = inputs.length;
console.log(counter);
var upload;
// if there is no input at all, or if the last one is already filled with a File
if (!last.length || last[0].files.length) {
console.log('create new input');
upload = makeNewInput();
} else {
// use the last one
upload = last;
}
//trigger to dialog open file
upload.trigger('click');
function makeNewInput(counter)  {
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
var el = $(html);
el.on('change', onuploadchange);
$('#result').append(el);
return el;
}
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>

How to change filename in a file input with AngularJS?

Is there any way to change choosen file name?
For example, I choose a file name img1. On choosing the file it have to change to dynamicname. Is there any way to change name?
<input type="file" fd-input/>
Here is a way to change a filename inside a directive:
app.directive('file', function() {
return {
scope: {
file: '='
},
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var files = event.target.files;
var file = files[0];
scope.file = 'New file name';
scope.$apply();
});
}
};
});
Use it as following:
<input type="file" file="param.file" />
JSFiddle demo
If you have access to FormData you can use append method to change file name.
Refer this doc for more information.
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
var data = new FormData();
var ext = files[0].name.match(/\.(.+)$/)[1];
var fileName = Math.random().toString(36).substr(2, 19) + "." + ext;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
//data.append("UploadedImage", files[0]); //if you want to pass default name
data.append("UploadedImage", files[0],fileName);
}
HTML code -
<input id="fileUpload" type="file" ng-file-accept="'.jpg , .jpeg ,.bmp , .gif ,.png'" accept="image/*" />

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