upload and preview file before uploading replacing last image issue - javascript

I am trying to upload image and previewing it one by one but it replace last image.
I want to keep adding up more and more images but only last image is showing in received $_FILES array
Keep all upload images in form and keep them previewing.
my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
<script>
$(function() {
var upload_count = 0;
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);
}
// input.files.append(input.files[i]);
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>

The reason why only last images is getting uploaded is that you are storing the images in an array because you have single file upload input.
If you want upload multiple images you have previewer on form submit you would need to store them in array i have named imagesToUpload
Once you have all the images previwed and ready to submit the form with images you have selected and previewed you have loop forEach through that array imagesToUpload and append those file data to formData.
You will then this formData to your backend and upload all the images on backend using ajax request.
Run snippet below to see that array is using .push function to store all your images you have previewed.
$(function() {
var upload_count = 0;
//Store images in array
var imagesToUpload = []
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);
}
// input.files.append(input.files[i]);
//Push images to array on preview
imagesToUpload.push(input.files[i])
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
console.log(imagesToUpload)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>

Related

JQuery : Display the list of Files selected and remove the ones before uploading

I am using a multi-file upload with a form in django. I want to diplay the selected files in a list and that the user is able to remove the files that he wants before uploading. There is a delet button for it.
I based on a post to do on Jquery. It works to display the files, and remove them from the list that is diplayed on the webpage. However the files that are removed are still uploaded even if the are not display in the list.
Thank you
var fileInput = document.getElementById('id_Filename');
var fileListDisplay = document.getElementById('fileselect');
var fileList = [];
var renderFileList, sendFile;
fileInput.addEventListener('change', function(evnt) {
fileList = [];
for (var i = 0; i < fileInput.files.length; i++) {
fileList.push(fileInput.files[i]);
}
renderFileList();
});
renderFileList = function() {
fileListDisplay.innerHTML = '';
fileList.forEach(function(file, index) {
var fileDisplayEl = document.createElement('p');
fileDisplayEl.innerHTML = `${file.name} <button data-index="${index}" class='deletfile'>X</button>`;
fileListDisplay.appendChild(fileDisplayEl);
});
};
$(document).on('click', '.deletfile', function() {
const index = $(this).attr('data-index');
fileList.splice(parseInt(index, 10), 1);
$(this).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
<div>
<input type="file" name="Filename" class="form-control" multiple="" onchange="javascript:updateList()" maxlength="255" id="id_Filename">
</div>
<div class="block-file-selection">
<p>Selected files:</p>
<div id="fileselect"></div>
</div>

Open file in Javascript from user-specified file name

I want to open a file in Javascript that the user selects from the local filesystem. I can get the file name but I don't know how to open it.
<form action='' method='POST' enctype='multipart/form-data'>
<input id="archiveFile" type='file' name='userFile'><br>
<script>
archiveFile.onchange = function (e)
{
console.log(archiveFile.value);
// open the file here
}
</script>
</form>
You need for the HTML5 FileReader Api, further information are there: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
here is a polyfill using Flash: https://github.com/Jahdrien/FileReader
This is a very well-made article: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
it explains almost everything.
working example:
function FileReaderCtrl() {
var self = this;
var field = document.getElementById('fieldFile');
var result = document.getElementById('result');
self.readFile = function(event) {
var res = event.target.result;
var image = '<img src="'+ (res || '') +'"/>';
result.innerHTML = image;
console.log(image);
};
field.onchange = function(event) {
var files = field.files;
var reader;
if(files.length < 1) {
return;
}
reader = new FileReader();
reader.onload = self.readFile;
reader.readAsDataURL(files[0]);
}
}
document.addEventListener('DOMContentLoaded', FileReaderCtrl);
#result {
width: 200px;
height: 200px;
background: lightcoral;
margin: 1em auto;
}
img {max-width: 100% }
<label for="fieldFile">Select an Image:<br><input type="file" id="fieldFile"/></label>
<div id="result"></div>
Substitute archiveFile.files for archiveFile.value. The value of an input type="file" element is not a FileList or File object
For historical reasons, the value IDL attribute prefixes the file
name with the string "C:\fakepath\"
archive.files would be the FileList object, from which you can iterate the selected File object or objects if multiple attribute is set at input type="file" element. For example, archiveFile.files[0] to view properties of individual File object
<form action='' method='POST' enctype='multipart/form-data'>
<input id="archiveFile" type='file' name='userFile'>
<br>
<script>
archiveFile.onchange = function(e) {
console.log(archiveFile.files, archiveFile.files[0]);
// open the file here
}
</script>
</form>

How to bind files to input[type="file"] in javascript

I have div which was dropzone to drop file(s) in the div,
<div id="dropZone"></div>
<input type="file" id=fileUpload"/>
I want to bind drop files to the html file type "fileUpload" control. I have tried like
but not getting. is it possible?
I have written the script for the div
$('#dropZone').bind('dragenter', ignoreDrag);
$('#dropZone').bind('dragover', ignoreDrag);
$('#dropZone').bind('drop', function (e) {
drop(e);
});
Edited and Added script
//Updated
function ignoreDrag(e) {
e.originalEvent.stopPropagation();
e.originalEvent.preventDefault();
}
//Updated End
and in the drop function
function drop(e) {
ignoreDrag(e);
var dt = e.originalEvent.dataTransfer;
var droppedFiles = dt.files;
if (dt.files.length > 0) {
for (var i = 0; i < dt.files.length; i++) {
var fileName = droppedFiles[0].name;
$("#lblMsg").show();
$("#spnFile").text(fileName);
var formData = new FormData();
formData.append("fileUploaded", droppedFiles);
alert(dt.files[0]);
$("#fileUploaded").bind("val", dt.files[0]);
// Binding to file(s) to the <input type="file"/> but not binding.
}
}
}
Is this possible to bind like above??

get width of uploaded image (before uploading file to server)

I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.
<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>
$("#filput").on('change', function () {
var w = $(this).width();
if (w < 500) {
alert("too small");
} else {
alert("big");
}
});
The this referrs to the input not the image. You have too use the HTML5 file API.
You can use this example: How to get the image width from html 5 file API
Code example: copied from: Getting Image Dimensions using Javascript File API
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});

Javascript Image Preview for page with lots of forms

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]

Categories

Resources