I need to add multiple images for upload. Below is my form. In the form, if you kindly check run code snippet`, when I upload image one by one, images with preview shown but no of images are not increased (here shows 2 files though total 4 images are present). but when I select multiple images at a time, then no of selected images shows.
In the attached image, it shows 4 images but no of count shows only 2 files. This is the problem.
I want to know, is it possible to increase no of files, when I choose images one by one i.e. with single click and select one image?
$(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\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
input[type="file"] {display: block;}
.imageThumb {max-height: 75px; border: 2px solid; padding: 1px; cursor: pointer;}
.pip {display: inline-block; margin: 10px 10px 0 0;}
.remove { display: block;background: #444;border: 1px solid black;color: white;text-align: center;cursor: pointer;}
.remove:hover {background: white;color: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple /></br>
<input type="submit" name="submit" value="Submit">
</div>
This is because you are relying on the browser's default <input>'s UI, which will only show its current content.
So if you want to upload all the Files that got selected, create an Array where you'll store all your Files, at every change.
Then to send it to your server, you will block the default behavior of your <form> by blocking its submit event, and sending a FormData filled with your files through XHR.
$(document).ready(function() {
// First define the Array where we will store all our files
var myFiles = [];
// now, every time the user selects new Files,
$("#files").on("change", function(e) {
var files = e.target.files, file;
// iterate through all the given files
for (var i = 0; i < files.length; i++) {
file = files[i];
myFiles.push(file); // store it in our array
$('<span class="pip">' +
'<img class="imageThumb" ' +
// no need for a FileReader here,
// a blobURI is better (sync & uses less memory)
'src="' + URL.createObjectURL(file) + '" ' +
'title="' + file.name + '"/>' +
'<br/>' +
'<span class="remove">Remove image</span>' +
'</span>')
.insertAfter("#files")
// add the event listener only on the new .remove
.find(".remove").click(removeFile.bind(null, file));
}
updateCounters();
});
// now override the default form submission
$('form').on('submit', upload);
// removes both the preview elements from doc and the file from our array
function removeFile(file, evt) {
$(evt.target).parent(".pip").remove();
myFiles.splice(myFiles.indexOf(file), 1);
updateCounters();
}
// ...
function updateCounters() {
$('#counter').text(myFiles.length + ' files selected');
}
// from submission overriding function
function upload(evt) {
evt.preventDefault(); // first block the default event
var fd = new FormData(); // create a new FormData
for (var i = 0; i < myFiles.length; i++) {
fd.append('files[]', myFiles[i]); // append all our files to it
}
// Post the formdata through XHR
var xhr = new XMLHttpRequest();
xhr.open('POST', 'YOUR_FORM_ACTION_URL');
// if you wanted to do something after the files are submitted
// xhr.onload = callback;
xhr.send(fd);
}
});
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Upload your images</h3>
<span id="counter">0 files selected</span>
<input type="file" id="files" name="files[]" multiple /><br>
<input type="submit" name="submit" value="Submit">
</div>
Related
I have an image previewer that uses the JavaScript Image() object to preview images prior to them being processed with PHP. I have a div that contains an 'x' SVG graphic that is targeted with a click event to delete the image.
In the code below at the bottom of the function it uses evt.target and essentially removes the parent element that each image is inside to delete the image if the user wishes to do so.
This all works OK on a visual level, but even if the images are deleted (and they are removed from the HTML), when the 'submit' element on the form is clicked to upload the images, any deleted images are still processed. From what I can gather the images are stored in memory and are processed from there.
I've tried setting the image itself (the thumbnailElement in the JavaScript) to null and setting its src attribute to an empty string but this isn't working.
What is the best way to prevent these deleted image previews from being processed?
In the code below I've swapped out the SVG graphic for the 'x' to the letter 'x' to make it easier to read.
NOTE: I've showed the entire image uploader below - but it is the final part of the JS underneath // Delete Images that is part I need help with.
Codepen: https://codepen.io/emilychews/pen/WNjZVGZ
const dropZone = document.getElementById('drop-zone'),
showSelectedImages = document.getElementById('show-selected-images'),
fileUploader = document.getElementById('standard-upload-files')
dropZone.addEventListener("click", (evt) => {
// assigns the dropzone to the hidden input element so when you click 'select files' it brings up a file picker window
fileUploader.click();
});
// Prevent browser default when draging over
dropZone.addEventListener("dragover", (evt) => {
evt.preventDefault();
});
fileUploader.addEventListener("change", (evt) => {
// Clear the already selected images
showSelectedImages.innerHTML = "";
// this function is further down but declared here and shows a thumbnail of the image
[...fileUploader.files].forEach(updateThumbnail);
});
dropZone.addEventListener("drop", (evt) => {
evt.preventDefault();
// Clear the already selected images
showSelectedImages.innerHTML = "";
// assign dropped files to the hidden input element
if (evt.dataTransfer.files.length) {
fileUploader.files = evt.dataTransfer.files;
}
// function is declared here but written further down
[...evt.dataTransfer.files].forEach(updateThumbnail);
});
// updateThumbnail function that needs to be able to handle multiple files
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
const uploadImageWrapper = document.createElement('article'),
removeImage = document.createElement('div'),
thumbnailElement = new Image();
// 'x' that deletes the image
removeImage.classList.add("remove-image");
removeImage.innerHTML = 'x';
// image thumbnail
thumbnailElement.classList.add("drop-zone__thumb");
thumbnailElement.src = URL.createObjectURL(file);
// appending elements
showSelectedImages.append(uploadImageWrapper) // <article> element
uploadImageWrapper.append(removeImage) // 'x' to delete
uploadImageWrapper.append(thumbnailElement); // image thumbnail
// Delete images
removeImage.addEventListener('click', (evt) => {
if(evt.target) {
var deleteImage = removeImage.closest('article');
deleteImage.remove()
}
})
}
} // end of 'updateThumbnail' function
body {
margin: 0;
display: flex;
justify-content: center;
width: 100%;
}
form {
width: 30%;
}
#drop-zone {
border: 1px dashed;
width: 100%;
padding: 1rem;
margin-bottom: 1rem;
}
.select-files {
text-decoration: underline;
cursor: pointer;
}
/* image that is preview prior to form submit*/
.drop-zone__thumb {
width: 200px;
height: auto;
display: block;
}
#remove-x {
width: 1rem;
height: 1rem;
}
#submit-images {
margin: 1rem 0;
}
#show-selected-images {
display: flex;
}
<form id="upload-images-form" enctype="multipart/form-data" method="post">
<h1>Upload Your Images</h1>
<div id="drop-zone" class="drop-zone flex">
<p class="td text-center">DRAG AND DROP IMAGES HERE</p>
<p class="td text-center" style="margin: 0">Or</p>
<p class="tl text-center select-files text-bold pointer">Select Files</p>
</div>
<input id="standard-upload-files" style="display:none" style="min-width: 100%" type="file" name="standard-upload-files[]" multiple>
<input type="submit" name="submit-images" id="submit-images" value="SUBMIT IMAGES">
<div id="show-selected-images"></div>
</form>
Problem:
You are not updating fileUploader.files when you add/remove an item.
Solution
Every time you drop/remove a file you need to update the fileUploader input. The first step is to create a function to handle the FileList object and change only two lines of your code:
//--> to create a FileList
function getFileListItems (files) {
var transferObject = new ClipboardEvent("").clipboardData || new DataTransfer()
for (var i = 0; i<files.length; i++) transferObject.items.add(files[i])
return transferObject.files;
}
Add files during the drop event:
//--> Updating files during drop event
fileUploader.files = getFileListItems([...fileUploader.files, ...evt.dataTransfer.files]);
Removing a file:
fileUploader.files = getFileListItems([...fileUploader.files].filter(f => file!==f));
See a complete working example:
const dropZone = document.getElementById("drop-zone"),
showSelectedImages = document.getElementById("show-selected-images"),
fileUploader = document.getElementById("standard-upload-files");
dropZone.addEventListener("click", (evt) => {
// assigns the dropzone to the hidden input element so when you click 'select files' it brings up a file picker window
fileUploader.click();
});
// Prevent browser default when draging over
dropZone.addEventListener("dragover", (evt) => {
evt.preventDefault();
});
fileUploader.addEventListener("change", (evt) => {
// this function is further down but declared here and shows a thumbnail of the image
[...fileUploader.files].forEach(updateThumbnail);
});
function getFileListItems(files) {
var transferObject = new ClipboardEvent("").clipboardData || new DataTransfer()
for (var i = 0; i < files.length; i++) transferObject.items.add(files[i])
return transferObject.files;
}
dropZone.addEventListener("drop", (evt) => {
evt.preventDefault();
// assign dropped files to the hidden input element
if (evt.dataTransfer.files.length) {
fileUploader.files = getFileListItems([...fileUploader.files, ...evt.dataTransfer.files]);
}
// function is declared here but written further down
[...evt.dataTransfer.files].forEach(updateThumbnail);
});
// updateThumbnail function that needs to be able to handle multiple files
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
let uploadImageWrapper = document.createElement("article"),
removeImage = document.createElement("div"),
thumbnailElement = new Image();
// 'x' that deletes the image
removeImage.classList.add("remove-image");
removeImage.innerHTML =
'<svg id="remove-x" viewBox="0 0 150 150"><path fill="#000" d="M147.23,133.89a9.43,9.43,0,1,1-13.33,13.34L75,88.34,16.1,147.23A9.43,9.43,0,1,1,2.76,133.89L61.66,75,2.76,16.09A9.43,9.43,0,0,1,16.1,2.77L75,61.66,133.9,2.77a9.42,9.42,0,1,1,13.33,13.32L88.33,75Z"/></svg>';
// image thumbnail
thumbnailElement.classList.add("drop-zone__thumb");
thumbnailElement.src = URL.createObjectURL(file);
// appending elements
showSelectedImages.append(uploadImageWrapper); // <article> element
uploadImageWrapper.append(removeImage); // 'x' to delete
uploadImageWrapper.append(thumbnailElement); // image thumbnail
// Delete images
removeImage.addEventListener("click", (evt) => {
if (evt.target) {
var deleteImage = removeImage.parentElement;
deleteImage.remove();
fileUploader.files = getFileListItems([...fileUploader.files].filter(f => file !== f));
}
});
}
} // end of 'updateThumbnail' function
body {
margin: 0;
display: flex;
justify-content: center;
width: 100%;
}
form {
width: 30%;
}
#drop-zone {
border: 1px dashed;
width: 100%;
padding: 1rem;
margin-bottom: 1rem;
}
.select-files {
text-decoration: underline;
cursor: pointer;
}
/* image that is preview prior to form submit*/
.drop-zone__thumb {
width: 200px;
height: auto;
display: block;
}
#remove-x {
width: 1rem;
height: 1rem;
}
#submit-images {
margin: 1rem 0;
}
#show-selected-images {
display: flex;
}
<form id="upload-images-form" enctype="multipart/form-data" method="post">
<h1>Upload Your Images</h1>
<div id="drop-zone" class="drop-zone flex">
<p class="td text-center">DRAG AND DROP IMAGES HERE</p>
<p class="td text-center" style="margin: 0">Or</p>
<p class="tl text-center select-files text-bold pointer">Select Files</p>
</div>
<input id="standard-upload-files" style="display:none" style="min-width: 100%" type="file" name="standard-upload-files[]" multiple>
<input type="submit" name="submit-images" id="submit-images" value="SUBMIT IMAGES">
<div id="show-selected-images"></div>
</form>
Working example
This is because when a form submitted, it doesn't submit every HTML element in the form, but only values of input, textarea, pressed button and some others that have name attribute.
So what you need is clear the file input field too:
const showSelectedImages = document.getElementById("preview");
const input = document.getElementById("test");
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
// image and 'x' to delete wrapper
const uploadImageWrapper = document.createElement('article')
// div that holds the 'x' to delete
const removeImage = document.createElement('div')
// image preview element
thumbnailElement = new Image()
// 'x' that deletes the image
removeImage.classList.add("remove-image")
removeImage.innerHTML = 'x'
// image thumbnail
thumbnailElement.classList.add("drop-zone__thumb")
thumbnailElement.src = URL.createObjectURL(file)
// appending elements
showSelectedImages.append(uploadImageWrapper) // <article> element
uploadImageWrapper.append(removeImage) // 'x' to delete
uploadImageWrapper.append(thumbnailElement) // image thumbnail
// Delete Images when the 'x' div is clicked
removeImage.addEventListener('click', (evt) => {
if (evt.target) {
var deleteImage = removeImage.parentElement
deleteImage.remove();
/* for single file input is enough clear value property */
// input.value = null;
/* for multiple files input we'll need recreate new files list excluding deleted file */
const dt = new DataTransfer();
for (let f of input.files) {
if (f !== file)
dt.items.add(f);
}
input.files = dt.files;
}
})
}
}
function updateThumbnails(files) {
showSelectedImages.innerHTML = ""; //remove all previous previews
for (let f of files)
updateThumbnail(f);
}
function showform(form) {
const list = {};
for (let i of [...new FormData(form).entries()]) {
const key = i[0].match(/^([^\[]+)\[\]$/);
if (key) {
if (!list[key[1]])
list[key[1]] = [];
list[key[1]][list[key[1]].length] = i[1];
} else
list[i[0]] = i[1];
}
console.log(list)
return false;
}
.remove-image {
cursor: pointer;
}
article {
display: inline-block;
}
<form type="post" onsubmit="return showform(this);">
<input type="hidden" name="myHiddenInput" value="blah">
<input type="file" name="test[]" id="test" oninput="updateThumbnails(this.files)" multiple>
<span id="preview"></span>
<button type="submit">submit</button>
</form>
I preview the pictures with ajax, that's okay, but when I add pictures on them again, there are the last additions to the FILES series.
Previous pictures disappear.
function previewImages(bu,p_id) {
var preview = document.querySelector('#image_multiple_block33');
//alert(preview.getAttribute("id"));
if (bu.files) {
[].forEach.call(bu.files, readAndPreview);
}
var files_id = bu.getAttribute("id");
var img_content_count;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " noo support file");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.width = 100;
image.title = file.name;
image.src = this.result;
var t = document.createElement('div');
t.className = 'image_content image'+p_id;
t.id = 'image'+p_id;
t.setAttribute("id", t.id);
t.innerHTML += '<div class="img_content_inner" id="img_content_inner'+p_id+'">'+
'<input type="text" name="image_color" placeholder="Product Color">'+
'<img src="'+image.src+'" width="'+image.width+'%" title="'+image.title+'" />'+
'<div class="multiple_img_del"><span onclick="multiple_image_del('+t.id+')">X</span></div>'+
'</div>';
//t.append(image);
//preview.appendChild(t);
var bu = preview.getAttribute("id");
var c = document.getElementById(bu).children.length;
var list = document.getElementById(bu);
list.insertBefore(t, list.children[1]);
// append files val
var fileSelect = document.getElementById(files_id);
var files = fileSelect.files;
var form_data = new FormData();
//alert(totalfiles);
for (var i = 0; i < files.length; i++) {
var fil = files[i];
if (!fil.type.match('image.*')) {
continue;
}
form_data.append("multiple_file[]", file, fil.name);
}
xhr = new XMLHttpRequest();
xhr.open("POST", "update/home-page-update.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(form_data);
});
reader.readAsDataURL(file);
}
}
.image_multiple {display: flex;flex-wrap: wrap;}
.image_content {flex: 0 33.333%;flex-wrap: wrap; max-width: 33.333%;padding: 20px; box-sizing: border-box;}
.image_content:first-child {flex: 0 100% !important;max-width: 100% !important;}
.image_content form {width: auto !important;}
.img_content_inner {border:1px dashed #ccc;padding: 10px;position: relative;}
.img_content_inner:hover .multiple_img_del {display: block;}
.multiple_img_del {position: absolute;right: 20px;bottom: 20px;display: none;}
.multiple_img_del span {display: block;background-color: orange; color: #fff;padding: 5px;width:30px;height:30px;line-height:30px;border-radius: 25px; cursor: pointer;}
.multiple_img_del span:hover {color: #111;}
.img_content_inner input[type="text"] {padding: 10px; width: 100%; box-sizing: border-box;margin-bottom: 10px; border: 1px solid #ccc;border-radius: 5px;}
.img_content_inner input[type="text"]:focus { border-color: #3f51b5 }
form#width_style {width:100%;box-sizing: border-box;}
.img_content_inner #multiple_label {cursor: pointer;}
<div class="image_multiple" id="image_multiple_block33">
<div class="image_content image_content<?php echo $urun_v->urun_id; ?>">
<div id="img_content_inner" class="img_content_inner">
<label for="multiple_images<?php echo $urun_v->urun_id; ?>" id="multiple_label">
<span class="img_symbol">📤</span>
</label>
<input id="multiple_images33" name="multiple_file_images[]" type="file" onchange="previewImages(this,'33')" multiple>
</div>
</div>
</div>
This is what I want to happen
When I choose the pictures for preview, I need to add a few more pictures, but when I add them, they are the latest in the FILES series.
2.I added picture color information to the area above the pictures. How do I relate to these pictures?
Finally the php tool:
white
Picture 1
Picture 2
Picture 4
Black
Picture 3
Picture 5
....
Finally save to database as json
check link for ajax image upload with preview.
https://www.nicesnippets.com/blog/php-ajax-image-upload-with-preview-example
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.
Here is my code:
var abc = 0; //Declaring and defining global increement variable
$(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();
}
});
});
#import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
background-color:white;
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family: 'Droid Sans', sans-serif;
}
#formdiv{
width:500px;
float:left;
text-align: center;
}
form{
padding: 40px 20px;
box-shadow: 0px 0px 10px;
border-radius: 2px;
}
h2{
margin-left: 30px;
}
.upload{
background-color:#ff0000;
border:1px solid #ff0000;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0px green;
box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
color:green;
padding:5px; border:1px dashed #123456;
background-color: #f9ffe5;
}
#upload{
margin-left: 45px;
}
#noerror{
color:green;
text-align: left;
}
#error{
color:red;
text-align: left;
}
.abcd{
text-align: center;
}
b{
color:red;
}
#formget{
float:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="maindiv">
<div id="formdiv">
<form action = "" enctype="multipart/form-data" action="" method="post">
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="text" required >
<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>
<!-- Right side div -->
</div>
And my php file:
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png", "pdf"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}}?>
using jquery and html5
<script type="text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
if (typeof (fileUpload.files) != "undefined") {
var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
alert(size + " KB.");
} else {
alert("This browser does not support HTML5.");
}
}
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Try something like this u will get
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
});
$("#approvedFiles").val(approvedHTML);
I am using this source: http://opoloo.github.io/jquery_upload_preview/
until now, I can upload one image with preview.
<style type="text/css">
.image-preview {
width: 200px;
height: 200px;
position: relative;
overflow: hidden;
background-color: #000000;
color: #ecf0f1;
}
input[type="file"] {
line-height: 200px;
font-size: 200px;
position: absolute;
opacity: 0;
z-index: 10;
}
label {
position: absolute;
z-index: 5;
opacity: 0.7;
cursor: pointer;
background-color: #bdc3c7;
width: 200px;
height: 50px;
font-size: 20px;
line-height: 50px;
text-transform: uppercase;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("image-preview").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
}
);
});
</script>
<!--| catatan penting: yang penting action="" & input type="file" name="image" |-->
<form action="upload.php" method="POST" enctype="multipart/form-data">
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<div class="image-preview">
<label for="image-upload" class="image-label">+ GAMBAR</label>
<input type="file" name="my_field[]" class="image-upload" />
</div>
<input type="submit"/>
</form>
then try to add more div class image preview, i want add another button with image preview. i don't want multiple upload with one button.
$(document).ready(function() {$.uploadPreview => use id, of course when change to class and add more div, when upload a button, another button will change. i am confused with the logic. Anyone can help? maybe using array but, i don't know how..
Since upload button is dependent on state of uploadPreview you need to initialize for each div separately to get separate upload buttons.
Change your html like this give each container a class say imgBox
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
.....
....
...
<div class="imgBox">
<label for="image-upload" class="image-label">Choose File</label>
<input type="file" name="image" class="image-upload" />
</div>
..
Now initialize each one using jquery each()
$(".imgBox").each(
function(){
$.uploadPreview({
input_field: $(this).find(".image-upload"),
preview_box: this,
label_field: $(this).find(".image-label")
});
});
I created a simple image uploading index.html file for image uploading and preview.
Needs j-query.No need of extra plugins.
If you have any questions ask me ;)
//to preview image you need only these lines of code
var imageId=idOfClicked;
var output = document.getElementById(imageId);
output.src = URL.createObjectURL(event.target.files[0]);
Check it here:
https://jsfiddle.net/chs3s0jk/6/
I have one better option for the file upload it's easy to use and you can try it.
window.onload = function(){
if(window.File && window.FileList && window.FileReader){
$(document).on("change",'.file', function(event) {
var files = event.target.files; //FileList object
var output = document.getElementById("upload-preview");
$("#upload-preview").html("");
if(files.length>5){
$(".file").after("<div class='alert alert-error'><span class='close'></span>Maximum 5 files can be uploaded.</div>");
$(this).val("");
return false;
}
else{
$(".file").next(".alert").remove();
}
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
// if(!file.type.match('image'))
if(file.type.match('image.*')){
if(this.files[0].size < 2097152){
// continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.className = "upload-preview-thumb";
div.style.backgroundImage = 'url('+picFile.result+')';
output.insertBefore(div,null);
});
//Read the image
$('#clear, #upload-preview').show();
picReader.readAsDataURL(file);
}else{
alert("Image Size is too big. Minimum size is 1MB.");
$(this).val("");
}
}else{
alert("You can only upload image file.");
$(this).val("");
}
}
});
$(".file2").change(function(event){
var err=0;
var input = $(event.currentTarget);
var ele = $(this);
var file = input[0].files[0];
var u = URL.createObjectURL(this.files[0]);
var w = ele.attr("data-width");
var h = ele.attr("data-height");
var img = new Image;
img.onload = function(){
if(w){
if(img.width!=w || img.height!=h){
ele.parent().find(".alert").remove();
ele.parent().find(".upload-preview").before("<div class='alert alert-error'>Please upload a image with specified dimensions.</div>");
ele.val("");
}
else{
ele.parent().find(".alert").remove();
}
}
};
img.src = u;
var nh;
if($(this).attr('data-preview')=='full')
nh = (h/w*150)
else
nh=150
var preview = ele.parent().find(".upload-preview");
var reader = new FileReader();
preview.show();
reader.onload = function(e){
image_base64 = e.target.result;
preview.html("<div class='upload-preview-thumb' style='height:"+nh+"px;background-image:url("+image_base64+")'/><div>");
};
reader.readAsDataURL(file);
});
}
else
{
console.log("Your browser does not support File API");
}
}
above code save as one js file like file-upload.js
then link it to your file where you want perview.
i.e.
<script src="js/file-upload.js" type="text/javascript"></script>
use this kind of example for the input type
<input type="file" class="file2" name="page-image" id="page-image"/>
that works on the class that name is "file2" that class you given to the input field that able to create preview.
full structure something like below.
HTML Code you can try
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
<input type="file" class="file2" name="page-image[]" id="page-image"/>
<div class="clearfix"></div>
<div class="upload-preview" style="display: block;">
<div class="upload-preview-thumb">
// perview genereate here
// you can display image also here if uploaded throw the php condition in edit image part
</div>
</div>
CSS
.upload-preview {
border: 1px dashed #ccc;
display: block;
float: left;
margin-top: 10px;
padding: 5px;
}
.upload-preview-thumb {
background-position: 50% 25%;
background-size: cover;
float: left;
margin: 5px;
position: relative;
width: 139px;
}
Hope this works and in future it's helpful for you.
Thanks.
hello, i need your help for my codes. I want to preview multiple images before upload and there are remove button in each images. But my code doesn't work when i'm using div targetting in each remove button.
the first, my codes is like THIS FIDDLE 1.
and when i'm add some changes become THIS FIDDLE 2
my HTML :
<body>
<header>
<h1>File API - FileReader</h1>
</header>
<article>
<label for="files">Select multiple files: </label>
<input id="files" type="file" multiple/>
<output id="result" />
</article>
and CSS :
body{
font-family: 'Segoe UI';
font-size: 12pt;
}
header h1{
font-size:12pt;
color: #fff;
background-color: #1BA1E2;
padding: 20px;
}
article
{
width: 80%;
margin:auto;
margin-top:10px;
}
.thumbnail{
height: 100px;
margin: 10px;
}
it's my javascripts :
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/> <a href='#' class='remove_pict'>X</a>";
output.insertBefore(div,null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
thanks for advance. any suggestions much be appreciated ^^
Image and delete anchor are children of div object. Put click event on each a, then delete the parent. So when user click the x mark, selected image will be deleted.
div.children[1].addEventListener("click", function(event){
div.parentNode.removeChild(div);
});
see demo at http://jsfiddle.net/L45LW/5/
$("#result").on( "click",".remove_pict",function(){
$(this).parent().remove();
});
This may be help you