I want to preview multiple images before upload. Secondly I want to remove/deselect the selected file if I choose wrong file. I am working on jquery code but it preview one image at a time. Also I want to select multiple images at a single time.
Here is the jquery code.
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Here is the HTML code
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" multiple type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
maybe you can see this topic , I think it has what you need.
Create live preview of image (before upload it) using JQuery
also you can give a try with that
http://www.aspsnippets.com/Articles/Show-Display-image-preview-before-upload-using-jQuery.aspx
You can find examples on http://www.fyneworks.com/jquery/multifile/
Maybe you can extract the parts of their code to write your custom.
For images preview you can use the URL.createObjectURL javascript function . Example:
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
var URL = window.URL || window.webkitURL;
var img = $('<img />').attr('src', URL.createObjectURL(this.files[0] ) );
}
});
If you need a full uploader you can also try this: http://www.albanx.com/ajaxuploader/ or other online examples
Related
I want to allow the user to upload only pdf files in two input files:
<form onsubmit='return checkExt()' action='upload.php' method='POST'>
<label>upload the first file</label>
<input type='file' name='fileToUpload' id='fileToUpload' required>
<label>upload the secondfile</label>
<input type='file' name='fileToUpload1' id='fileToUpload1' required>
</form>
I used the following script to check the extension of the files-to-upload:
<script>
function checkExt() {
var allowedFiles = [".pdf"];
var form_valid = document.getElementById("fileToUpload");
var form_valid2 = document.getElementById("fileToUpload1");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test((form_valid.value.toLowerCase()) &&(form_valid2.value.toLowerCase()))) {
alert('only PDF files are allowed');
return false;
}
return true;
}
</script>
the problem is: when I test it, it only checks on the first file if it is a pdf or not. it does not check on the second file.
You don't need javascript to validate the filetypes. Just use to accept attribute in the input tag.
See documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
<input name="myFile" type="file" accept=".pdf" multiple>
Your second check in the if condition should mirror the first one and this is the reason why it doesn't work.
Anyway the easiest and scalable way is to iterate over input fields of type "file". Like this:
function checkExt() {
var fileInputs = document.querySelectorAll('input[type="file"]');
var isValid = true;
var allowedFiles = [".pdf"];
var regex = new RegExp(
"([a-zA-Z0-9s_\\.-:])+(" + allowedFiles.join("|") + ")$"
);
fileInputs.forEach(function(input) {
if (!regex.test(input.value.toLowerCase())) {
isValid = false;
}
});
if (isValid) {
alert("only PDF files are allowed");
}
return isValid;
}
This allows you to add as many file input fields as you want.
I have found a code on internet to upload multiple images. While you select the image, it will show the selected image just below as preview, now the problem is what if I selected the wrong image and I want to remove that particular image, also no more than 4 image should be allowed
hope you get what I want to say below is the code
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
and jquery for the code is
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
The file list of HTML5 file input is readonly. So it's not possible to remove a single file out from a multiple file selection.
It's perfectly fine to empty a file input by resetting the form. You just can't modify it. So if you use 4 seperate single file selections, it's a simple matter of clearing the one that's being removed by the user:
HTML:
<form>
<input type="file" name='images[]' class="gallery-photo-add" id='image1' />
<input type="file" name='images[]' class="gallery-photo-add" id='image2' />
<input type="file" name='images[]' class="gallery-photo-add" id='image3' />
<input type="file" name='images[]' class="gallery-photo-add" id='image4' />
</form>
<div class="gallery"></div>
JS:
$(function() {
// Multiple images preview in browser
var imagesPreview = function(placeToInsertImagePreview) {
// Empty preview so we can safely rebuild it
$(placeToInsertImagePreview).empty();
// Get all files
var elems = document.getElementsByClassName("gallery-photo-add");
// Loop through each file and append them to the preview if available
for (i = 0; i < elems.length; i++) {
if (elems[i].files.length != 0) {
var reader = new FileReader();
var id = $(elems[i]).attr('id');
reader.onload = (function(id) {
return function(e){
$($.parseHTML('<img>')).attr({
'src' : e.target.result,
'data-id' : id
}).appendTo(placeToInsertImagePreview);
}
})(id);
reader.readAsDataURL(elems[i].files[0]);
}
}
};
// Temporarely wrap a form element around the input to reset it
window.reset = function(e) {
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
}
$('div.gallery').on('click', 'img', function() {
var id = $(this).attr("data-id");
reset($('#'+id));
$(this).remove();
});
$('.gallery-photo-add').on('change', function() {
imagesPreview('div.gallery');
});
});
You can test it here: https://jsfiddle.net/81nytqsc/2/
$('div.gallery').on('click','img',function(){
var files= $('#gallery-photo-add).get(0).files;
for(i=0;i<files.length;i++){
if(files[i]==$(this).attr('src')){
files= jQuery.grep(files, function(value) {
return value != files[i];
}
}
}
$(this).remove();
});
I'm trying to create an AngularJS form. One part of the form is taking the Base64 from a file and storing it to my $scope.user. However, clicking a file upload input and selecting my file is submitting my form, which should not be happening.
Here's my form:
<form ng-submit="processForm()" name="merchApp" style="position:relative">
<div class="form-section" ui-view>
<div class="row">
<div class="col-sm-12 text-center">
<button href="#" ng-click='docUpload("userId")'>Upload File</button> {{user.uploadIdName}}
<br/>* Accepted file types: .jpg, .png, .gif, .pdf, .doc, .docx
<br/>
(Max file size: 2MB)
<br/>
<input ng-model="user.uploadId" type="hidden" value="{{user.uploadId}}" required>
<br/><br/>
<button type="submit" class="next" ng-disabled="merchApp.$invalid">SUBMIT APPLICATION</button>
</div>
</div>
</div>
</form>
Here's my app.js
.controller('formController', ['$scope', '$http', '$parse', function($scope, $http, $parse) {
// we will store all of our form data in this object
$scope.user = {};
$scope.docUpload = function() { //default function, to be override if browser supports input type='file'
$scope.data.alert = "Your browser doesn't support HTML5 input type='File'"
}
var fileUploadScope;
var fileSelect = document.createElement('input'); //input it's not displayed in html, I want to trigger it form other elements
fileSelect.type = 'file';
if (fileSelect.disabled) { //check if browser support input type='file' and stop execution of controller
return;
}
var fileUploadScope;
var fileUploadName;
$scope.docUpload = function(x) { //activate function to begin input file on click
switch(x){
case "checkBankLetter":
fileUploadScope = $parse("uploadCheckBankLetter");
fileUploadName = $parse("uploadCheckBankLetterFileName");
break;
case "userId":
fileUploadScope = $parse("uploadId");
fileUploadName = $parse("uploadIdName");
break;
default:
alert ("error");
}
fileSelect.click();
}
fileSelect.onchange = function() { //set callback to action after choosing file
var f = fileSelect.files[0];
var fsize = f.size;
var fileTypes = ['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf', 'gif'];
if (fsize > 2097152){//file size limit is 2MB
alert ("File size too large. Please select a file 2MB or smaller.");
}
else {// file size is acceptable
if(f){
var extension = f.name.split('.').pop().toLowerCase(), //file extension from input file
isSuccess = fileTypes.indexOf(extension) > -1; //is extension in acceptable types
if (isSuccess) { //yes
var r = new FileReader();
r.fileName = f.name;
if (typeof FileReader !== "undefined"){
r.onloadend = function(e) { //callback after files finish loading
// allow for different scope names for file upload functions
fileUploadScope.assign($scope.user, e.target.result);
fileUploadName.assign($scope.user, r.fileName);
$scope.$apply();
//here you can send data over your server as desired
}
r.readAsDataURL(f); //once defined all callbacks, begin reading the file
}
}
else {
alert("Please select an acceptable file type");
}
}
}
};
// function to process the form
$scope.processForm = function() {
$http({
method : 'POST',
url : 'docusign.php',
data : $scope.user // pass in data as strings
})
.success(function(data) {
console.log(data);
location.replace(data);
});
};
}])
processForm() is firing after I click <button href="#" ng-click='docUpload("userId")'>Upload File</button> and select a file, and I can't figure out why this is happening.
Ideally it is better practice to specify type attribute for buttons.
button without type attribute acts as submit buttons that is reason your form getting submitted when you click on button.
So add type attribute to button.| type="button"
remove href attribute since it is unnecessary for button.
Change this line
<button href="#" ng-click='docUpload("userId")'>Upload File</button>
to
<button type="button" ng-click='docUpload("userId")'>Upload File</button>
I'm not sure if this is best practices, but I was able to fix my problem by adding onclick="return false" to my input button.
How to get image instead of image name in html using file input type. I have used the css file for positioning the image file. I have tried all the sorts of code given... Please help.
<input type="file" name="photo" id="photo" onchange="readURL()"/>
function readURL()
{
document.getElementById('previewimage').style.display='block';
}
function readURL()
{
if (document.getElementById('photo').files && document.getElementById('photo').files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('previewimage').src = e.target.result;
};
reader.readAsDataURL(document.getElementById('photo').files[0]);
}
}
function openFiledialog(){
document.getElementById('photo').click();
}
//
<input type='button' onclick='openFiledialog()' value='photo'/>
<input type="file" style='display:none;' name="photo" id="photo" onchange="readURL()"/>
i have a form like this:
<form method=post src=upload enctype="multipart/form-data">
<input name="img1" id="img1" type="file">
<input type="submit" value="Upload">
</form >
Please how can I valid this form using javascript so that only jpg files are uploaded. thanks for reading.
You can bind the onsubmit event of your form, and check if the value of your file input ends with ".jpg" or ".jpeg", something like this:
window.onload = function () {
var form = document.getElementById('uploadForm'),
imageInput = document.getElementById('img1');
form.onsubmit = function () {
var isValid = /\.jpe?g$/i.test(imageInput.value);
if (!isValid) {
alert('Only jpg files allowed!');
}
return isValid;
};
};
Check the above example here.
Form :-
<form method=post src=upload enctype="multipart/form-data" onsubmit="return validateFile()">
<input name="img1" id="img1" type="file">
<input type="submit" value="Upload">
</form>
Javascript Code:-
function validateFile()
{
var allowedExtension = ['jpeg', 'jpg'];
var fileExtension = document.getElementById('img1').value.split('.').pop().toLowerCase();
var isValidFile = false;
for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}
if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}
return isValidFile;
}
if you want to add more image extensions please add in allowedExtension array;
var allowedExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
Array of the image extensions
let allowedExtension = ['image/jpeg', 'image/jpg', 'image/png','image/gif','image/bmp'];
get the type of image
//----<input type="file" id='userimage' accept="image/*" name='userimage'>-----
let type = document.getElementById('userimage').files[0].type;
check type have included inside the allowed extension array :)
if(allowedExtension.indexOf(type)>-1)
{
alert('ok')
}else{
alert('Not a image')
}
}
This is a simpler and more robust way to validate an image, and you don't have to think about all the possible image extensions out there.
document.body.querySelector('input[type="file"]')
.addEventListener('change', function () {
if (this.files[0] && this.files[0].type.includes('image')) {
console.log('file is an image');
} else {
console.log('file is not an image');
}
});
If you want strictly jpg
document.body.querySelector('input[type="file"]')
.addEventListener('change', function () {
if (this.files[0] && this.files[0].type === 'image/jpeg') {
console.log('file is jpg');
} else {
console.log('file is not jpg');
}
});
You can use the "accept" paramter to the input tag:
<input name="img1" id="img1" type="file" accept="image" />
Its not JavaScript but should still be helpful to prevent the user from even attempting to upload a non-image file.
A Google search unearthed this: http://www.webdeveloper.com/forum/archive/index.php/t-104406.html
For your application, I would recommend running the input through:
function valid(a){
return a.indexOf(".jpg") != -1 && a.type == file;
}
That should work.
71944 has some javascript that looks like it might do what you need. Bear in mind that it's only client side validation, so you'll still want to validate it on the server too.
<script>
var fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change",function(event){
document.getElementById("name").innerHTML = "NAME: " + event.target.files[0].name;
document.getElementById("type").innerHTML = "TYPE: " + event.target.files[0].type;
document.getElementById("size").innerHTML = "SIZE: " + event.target.files[0].size;
});
</script>
<input type="file" id="fileInput" name="file"/>