How can i save multiple IMGs after page refreshing? - javascript

There is a code of localStorage, i can add multiple images and only one image left after refreshing the page. How can I put all the pictures after refreshing?
This is the code on JSFiddle
I also created a code snippet here:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
localStorage.setItem('img', e.target.result);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
if(localStorage.img) {
var span = document.createElement('span');
span.innerHTML += ['<img class="thumb" src="', localStorage.img,
'" title="test"/>'].join('');
document.getElementById('list').insertBefore(span, null);
}
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

You're overwriting the localstorage key on line:
localStorage.setItem('img', e.target.result);
You can only have unique keys in localstorage and its values must be strings. So for saving multiple image you can:
Create a unique key for each image
Create an array for storing the imgs and then save it into localstorage under one key using JSON.stringify()
I've created this helper functions to save and retrieve the imgs from localStorage. Hope it helps:
function saveImgToStorage(img) {
let imgs = localStorage.getItem('imgs');
let imgsArray = imgs ? JSON.parse(imgs) : [];
imgsArray.push(img);
localStorage.setItem('imgs', JSON.stringify(imgsArray))
}
function getImgsFromStorage () {
return JSON.parse(localStorage.getItem('imgs'))
}
Also note that since the value returned from getImgsFromStorage() is an array, you need to make a loop to append each image to the document

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

Is there any way to manipulate elements by ID or class in a different file in the same directory?

I want to know whether it's possible to select and manipulate elements of a given ID or class in a different HTML file in the same directory. For example, like using getElementById but in a different file.
Assuming these files are on the local machine:
For loading the file:
<input type="file" id="files" name="files[]" multiple />
<textarea id="loadedFileArea"></textarea>
<script>
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = function(event)
{
// NOTE: event.target point to FileReader
var contents = event.target.result;
document.getElementById('loadedFileArea').innerText = contents;
// var lines = contents.split('\n');
//////
// document.getElementById('container').innerHTML=contents;
};
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
For saving this back, check out FileSaver.js You just need to turn the text (html) contents of loadedFileArea into a blob and pass that into FileSaver.saveAs

Get file names while displaying and before uploading on server using html and jquery

I am selecting multiple images using html tag 'input file multiple html' as below.
#Html.TextBoxFor(model => model.files, "",
new {#id = "filesToUploadID", #type = "file", #multiple = "multiple" })
<div class="col-md-10" id="selectedFiles"></div>
Then in javascript, I attached 'onchange' event listner to the above tag. When I select multiple images, I get all the attached images to the tag using jquery. But I need image file names as well. While getting image file names, I get only one file name poplulated in my html along with image using jquery.
jquery/ javascript is below
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#filesToUploadID').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
debugger;
NameArray = [];
if (!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
NameArray.push(f.name);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<img src='" + e.target.result + "' />";// + "<div>" + + "</div>";//+ "<br clear=\"left\"/>";
$(selDiv).append($(html));
//selDiv.innerHTML += html;
}
reader.readAsDataURL(f);
}
}
I tool help from this link and implemented both ways but could not succeed.
All images names are relevant to the images. What I am getting is like this
It's source code is
I have to assign id's based on image names that's why it is important to get relevant image names. Any lead to the topic will be high appreciated.
Thank you.
var f = files[i];
var fileName = e.target.f.name

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>

javascript FileReader get name?

I'm working on a simple script for my site to upload images. I have a multiple file input <input type = 'file' name = 'files[]' id = 'hiddenFile' multiple> that is being triggered by a div click. When I queue the files, I want to be able to delete one. I know I can loop through the $('#hiddenFile').val() and splice to get the name out but I'm having an issue with figuring out the file name. When I assign the file to a new img container, how do I get the name? I've tried console.log(f.name) and a few variations but it returns an undefined error. Here are my scripts. I think I'm pretty close but this is something I'm learning as I go. Thanks!
function readURL(input) {
var files = $('#hiddenFile')[0].files; //where files would be the id of your multi file input
//or use document.getElementById('files').files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(f.name); //how can I get the
//file name here to add it to the image as an attribute?
$("<img src = '"+e.target.result+"' class = 'addedImg'>").appendTo("#imgBox");
};
reader.readAsDataURL(f);
}
}
$(document).ready(function(){
$(document).on('click', '#addBtn', function(e){
e.preventDefault();
$('#hiddenFile').click();
});
});
Try using change event , defining f within an IIFE , setting title attribute value to f.name
$(document).ready(function() {
$(document).on('click', '#addBtn', function(e) {
e.preventDefault();
$('#hiddenFile').click();
});
$("#hiddenFile").change(function(event) {
var files = this.files;
var i = 0,
len = files.length;
(function readFile(n) {
var reader = new FileReader();
var f = files[n];
reader.onload = function(e) {
console.log(f.name);
$("<img src=" + e.target.result + " class=addedImg title=" + f.name + ">")
.appendTo("#imgBox");
// if `n` is less than `len` ,
// call `readFile` with incremented `n` as parameter
if (n < len -1) readFile(++n)
};
reader.readAsDataURL(f); // `f` : current `File` object
}(i)); // `i` : `n` within immediately invoked function expression
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="addBtn">click</div>
<input type="file" style="display:none" id="hiddenFile" multiple />
<div id="imgBox"></div>
The FileReader object itself does not have access to the file name. You get the file name while you're iterating over the files list as you are doing in your for loop.
var reader = new FileReader();
reader.onload = function (e) {
//update image src or something
};
for (var i = 0, f; f = files[i]; i++) {
reader.readAsDataURL(f); //updates image src or something
//additional method to do something with file name goes here
}
And if you really want to have one method that does those two things in the for loop, then you can wrap it all up in a closure like #ebidel does in his answer here - Get filename after filereader asynchronously loaded a file#answer-12547471.

Categories