I have the following html setup and cannot solve this issue.
When a button in the html document gets clicked, an element
<div id='wrapper'>
<input id='fileUpload' name='fileUpload' type='file' onchange='uploadpreview(this.id)' multiple />
<br />
<div id='image-holder'></div>
</div>
gets added using the function
function add(){
$j("<?php echo($divoutput)?>").insertBefore("#addbox");
}
(the php code has the html format in there).
However when this is done, the javascript function (Which is already in the html document and does not get added via a code) does not work:
$("#fileUpload").on('change', uploadpreview() {
//Get count of selected files
var countFiles = upload[0].files.length;
var imgPath = upload[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
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) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL(upload[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
}
It throws an error that length cannot be read etc, even though a file has been uploaded.
What can be the trouble of this?
I have tried the code separately (without being added via a code) and everything works flawlessly.
Please help!
Ok so let see if i understand you are adding stuff to the dom and wish to bind events to the newly added elements. if thats the case bind the events with the body so it "scans" from body down like this
$('body').on( 'change', '#fileUpload', function() {
DoSomething();
});
hope ite helps
Related
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;
}
On multiple image preview js code i have :
$(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;
$("<li class=\"pip\"><figure>" +
"<img height='70px' width='70px' src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<a href='#' class='remove'><img src='' alt=''></a>" +
"</figure></li>").appendTo(".gallery");
$(".remove").click(function(){
alert('ok')
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
console.log(files);
});
}
});
Html code where i am appending this is :
<div class="uploaded-files">
<ul class="gallery">
</ul>
</div>
After all i am getting this .but my issue is that when i am deleting the image through cross icon it is not deleting the image i dont know why this is happening delete button is not working can please any one help me related this ??
Also i am not getting the file name in title
You need .parents() (plural) or closest to get to the .pip parent
parent: This method is similar to .parents(), except .parent() only travels a single level up the DOM tree.
Move the click to outside and delegate
$(function() {
$(".gallery").on("click",".remove",function(){
$(this).closest(".pip").remove();
});
$(".files").on("change", function(e) { ... })
});
You can remove
if (window.File && window.FileList && window.FileReader) {
since they exists since IE10
Lastly check this
How to get the filename from the Javascript FileReader?
To remove from the list, you need to make an array of it
$(function() {
let files;
$(".gallery").on("click", ".remove", function() {
const idx = $(this).closest("li").index(); // or set a data-attribute on the remove containing the IDX
$(this).closest(".pip").remove();
files.splice(idx,1)
console.log(files.map(f => f.name))
});
$(".files").on("change", function(e) {
files = [...e.target.files]; // create an array
$(".gallery").empty()
files.forEach(f => {
const fileReader = new FileReader();
fileReader.onload = (function(e) {
let file = e.target;
$(`<li class="pip"><figure>
<img height='70px' width='70px' src="${file.result}" title="${file.name}"/>
</i>
</figure></li>`).appendTo(".gallery");
});
fileReader.readAsDataURL(f);
})
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" class="files" multiple />
<ul class="gallery" style="list-style-type:none"></ul>
Code looks good, you seem to be missing a semicolon here:
alert('ok'); // <-- HERE
$(this).parent(".pip").remove();
im basic developer just wanted to push images one after other when an new image is been selected by user ,
following is my javascript :-
preview.js
<script language="javascript" type="text/javascript">
$(function () {
$("#fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height: 100px; width: 100px; margin-top: 20px;");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
</script>
Html
Index.html
<div id='file'>
<label for="fileupload" style="margin-right:5px;">Group Image/Logo</label><br>
<input id="fileupload" type="file" multiple="multiple"/>
<div id="dvPreview">
</div>
</div>
This code displays the image perfectly , but only in single instance( thumbnail gets changed every time he selects an image) .
What is neccessary to just push & show the thumbnail of all the images that user wants to upload ? .
Searching google , Points which can be usefull :-
using Array &
using foreach loop
Any one can explain the proper syntax ? It would be great . Thank you .
JSFIDDLE
Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validator but to no avail... This is a snippet from my current code:
<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />
Script:
App.Dispatcher.on("uploadpic", function() {
$(":file").change(function() {
if (this.files && this.files[0] && this.files[0].name.match(/\.(jpg|jpeg|png|gif)$/) ) {
if(this.files[0].size>1048576) {
alert('File size is larger than 1MB!');
}
else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
} else alert('This is not an image file!');
});
function imageIsLoaded(e) {
result = e.target.result;
$('#image').attr('src', result);
};
});
It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!
Try something like this:
JavaScript
const file = this.files[0];
const fileType = file['type'];
const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
if (!validImageTypes.includes(fileType)) {
// invalid file type code goes here.
}
jQuery
var file = this.files[0];
var fileType = file["type"];
var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
if ($.inArray(fileType, validImageTypes) < 0) {
// invalid file type code goes here.
}
You don't need jquery here.
var mimeType=this.files[0]['type'];//mimeType=image/jpeg or application/pdf etc...
//ie image/jpeg will be ['image','jpeg'] and we keep the first value
if(mimeType.split('/')[0] === 'image'){
console.log('the file is image');
}
You can also create a function to check when a file is image.
function isImage(file){
return file['type'].split('/')[0]=='image');//returns true or false
}
isImage(this.file[0]);
Update (es6)
using es6 includes method, makes it even more simple.
const isImage = (file) => file['type'].includes('image');
Pls refer a related query here. The answer here suggests to load the image in an Image object and check for it's width and height properties to be non zero.
I think the technique can be used to solve your problem too.
I also worked out a fiddle for you to refer. Pertinent code below:
var img = new Image();
img.addEventListener("load",function(){
alert('success');
});
img.addEventListener("error",function(){
alert('error');
});
img.src = picFile.result;
Here is a quick tip if you just want to know if the file is an image:
var file = this.files[0];
var fileType = file["type"];
if (fileType.search('image') >= 0) {
...
}
What I want to do is to check the actual file type
Try accessing files[0].type property . See Using files from web applications
$(":file").on("change", function(e) {
console.log(this.files[0].type);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />
If anyone comes here who is using jQuery Validator, a simple method would be:
jQuery.validator.addMethod(
"onlyimages",
function (value, element) {
if (this.optional(element) || !element.files || !element.files[0]) {
return true;
} else {
var fileType = element.files[0].type;
var isImage = /^(image)\//i.test(fileType);
return isImage;
}
},
'Sorry, we can only accept image files.'
);
which is then added to the .validate() function.
A lot of convoluted answers here.
Simply check whether the file has an image mime-type (which would be of the format image/...
const isImage = file => file.type.startsWith("image/")
$('#direct_upload').change(function() {
if (this.files[0].type.includes('image')) {
document.getElementById('attach_file').src = window.URL.createObjectURL(this.files[0])
} else {
console.log('it is a doc');
}
}
You could try to convert file type in string and after that slice this string like that:
if(String(file.type).slice(0, 6) === 'image/') {....some code}
Using jQuery version 3.3.1:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<label class="custom-file-label" for="customFile">Select Image</label>
<br>
<input type="file" class="custom-file-input" id="customFile">
</body>
<script>
$(document).ready(function() {
$(document).on("change", ".custom-file-input", function() {
var myImg = this.files[0];
var myImgType = myImg["type"];
var validImgTypes = ["image/gif", "image/jpeg", "image/png"];
if ($.inArray(myImgType, validImgTypes) < 0) {
alert("Not an image")
} else {
alert("Is an image")
}
});
});
</script>
</html>
I created this function for next and previous button, in other words there are 2 buttons in my html page and when i click next or previous the pages in the monocle will also move accordingly,
i read that i have to use a custom page flipper for this but they have not provided an example of how to create one.
this is what i've tried and fails:
function fileSelected(event,str) {
var thefile = document.getElementById('file');
var tval = thefile.value;
var ext = tval.split('.').pop();
var files = event.target.files;
var fname = tval.split(/(\\|\/)/g).pop();
if (ext == "epub" || ext == "EPUB"){
function createReader(bookData) {
Monocle.Reader("reader", bookData);
}
new Epub(files[0], createReader);
}else if(ext == "htm" || ext == "htm" || ext == "html" || ext == "HTML"){
var bookData = {
getComponents: function () {
return [
fname
];
},
getContents: function () {
return [
{title: "test", src: fname}
]
},
getComponent: function (componentId) {
return {url:componentId};
},
getMetaData: function(key) {
return {
title: "Test documents",
creator: "Aron Woost"
}[key];
}
}
window.reader = Monocle.Reader('reader', bookData);
}else{
return false;
}
}
function next(){
Monocle.Reader('reader', {}, {}, function (reader) {
reader.moveTo({ direction: 1 });
});
}
when clicking next will give an undefined error in my console.
any idea as how to implement a custom page flipper?
https://github.com/joseph/Monocle/wiki/Page-flippers
I am not that savvy in JS. sorry :(
I think the problem is in this block of variable declaration:
var thefile = document.getElementById('file');
var tval = thefile.value;
var ext = tval.split('.').pop();
var files = event.target.files;
var fname = tval.split(/(\\|\/)/g).pop();
Is there any input field with 'value' property applicable, like <input type="text" id="file"> ?
You sure the filename will certainly have a dot in it, i.e. extension?
Also event.target.files looks suspicious.
If there's nothing wrong, please tell which line the console shows error at. You can double click on the error to have the erroneous line highlighted.