How to delete from an object FileList - javascript

The function of this code, the preview image is displayed after selecting the file. Also internally, each key and value is inserted into the FileList object.
Each image displayed as a preview has a delete button. So, when you press it, the image disappears from the screen, and internally, I want to delete the corresponding key and value from the FileList object. I knew that I could delete from Object, like a " delete Object.key ; " However, in this case, this does not work effectively. Perhaps there are other different solutions to it. Please let me know if you know if
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<form id='form' action="data.php" method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<button class="show">Butoon</button>
</form>
<output id="list"></output>
<script>
$('output').on('click','.del',function(){
var id = $(this).prev().attr('id');
id = id.split("_");
id= id[1];
var x = document.getElementById("files").files;
if(id in x) {
delete x[' + id + '];  //This line is a problem.
}
console.dir(x);
$(this).parent().replaceWith();
});
function handleFileSelect(evt) {
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, num) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<div class="view"><img id ="img_' + num + ' " class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/><div class="del">×</div></div>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f, i);
reader.readAsDataURL(f);
}
console.dir(files);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>

Replace delete x[' + id + ']; with:
x.splice(id,1);

Related

Certain PDF files won't open

I'm having a weird issue I created an app to open PNG and PDF's. The problem is when I try to open PDF files larger than 2,000 Kb it will not display, however PNG's have no problem. I'm confused as too why this is.
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="styles.css">
</head>
<body>
<ul>
</ul>
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000">
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="file-select[]" multiple="multiple">
<div id="filedrag" style="display: block;">or drop files here</div>
</div>
<div id="submitbutton" style="display: none;">
<button type="submit">Upload Files</button>
</div>
<div id="sortbutton">
<button type="submit">Submit</button>
</div>
<div id="resetbutton">
<button type="submit">Reset</button>
</div>
</fieldset>
</form>
<div id="messages">
</div>
<script src="filedrag.js"></script>
</body></html>
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("application") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<object data="' + e.target.result + '"></object></p>');
}
reader.readAsDataURL(file);
}
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" height="500px" width="500px"></p>');
}
reader.readAsDataURL(file);
}
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton");
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
As I said you try to post a PDF file larger than 2000 Kb it will not display, PNG however will display
I fixed it I hardcoded the path to display the Files
I had the same issue like yours and I resolved in this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>

How to Pass Textbox Value from One Page to another?

I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))

Display multiple progress bar with multiple file upload using jquery,html and css

I use one browse button to select multiple files to upload but only 1 progress bar display for all uploaded files. Please review the following code:
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<style>
.a{
display:none;
}
</style>
</head>
<body>
<form id="myForm" method="post" enctype="multipart/form-data" ">
Files: <input type="file" id="files" name="files" multiple><br/>
<div id="selectedFiles"></div>
<progress class='a' max=100 value=10></progress>
<input type="submit" >
</form>
<script>
var selDiv = "";
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#files').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
if (!e.target.files)
return;
selDiv.innerHTML = "";
var files = e.target.files;
var elements = document.getElementsByClassName('a');
for (var i = 0; i < files.length; i++) {
var f = files[i];
var p = elements[0];
selDiv.innerHTML += f.name + "<br>";
p.style.display = 'block';
setInterval(function () {
var a = p.value;
a = a + 10;
//document.write(a);
p.value = a;
}, 1500);
}
}
</script>
</body>
</html>
I have to display separate progress bar for separate file upload.
Try this:
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<style>
.a{
display:none;
}
</style>
</head>
<body>
<form id="myForm" method="post" enctype="multipart/form-data">
Files: <input type="file" id="files" name="files" multiple><br/>
<div id="progress-wpr">
<div class="filename"></div>
<progress class='a' max=100 value=10></progress>
</div>
<input type="submit" >
</form>
<script>
var selDiv = "";
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#files').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(e) {
if(!e.target.files) return;
var files = e.target.files;
for(var i=1; i<files.length; i++) {
var progress = document.createElement("progress");
progress.setAttribute('class','a');
progress.setAttribute('max','100');
progress.setAttribute('value','100');
var filename = document.createElement("div");
filename.setAttribute('class','filename');
document.getElementById('progress-wpr').appendChild(filename);
document.getElementById('progress-wpr').appendChild(progress);
}
var elements = document.getElementsByClassName('a');
var filename = document.getElementsByClassName('filename');
for(var i=0; i<files.length; i++) {
var f = files[i];
var p=elements[i];
filename[i].innerHTML = f.name;
p.style.display='block';
setInterval(update_progress, 1500);
}
}
function update_progress(){
var elements = document.getElementsByClassName('a');
for(var i=0; i<elements.length; i++) {
var p=elements[i];
var a=p.value;
a=a+10;
p.value=a;
}
}
</script>
</body>
</html>
Updated
update_progress() function added
Although you assigned:
var p=elements[0];
you multiple variable p is refer to the same elements[0], which is
<progress class='a' max=100 value=10></progress>
on your page, you should dynamically create multiple elements for the progress bar.

how to display image in file upload dynamically

I have created a function for file upload. I get the file name and file type and don't know how to display image using dynamic control!
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file"/>' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
Here's some code from a for-fun project I have.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('mFileInput').addEventListener('change', onFileChosen, false);
}
// fileVar is an object as returned by <input type='file'>
// imgElem is an <img> element - can be on/off screen (doesn't need to be added to the DOM)
function loadImgFromFile(fileVar, imgElem)
{
var fileReader = new FileReader();
fileReader.onload = onFileLoaded;
fileReader.readAsBinaryString(fileVar);
function onFileLoaded(fileLoadedEvent)
{
var result,data;
data = fileLoadedEvent.target.result;
result = "data:";
result += fileVar.type;
result += ";base64,";
result += btoa(data);
imgElem.src = result;
imgElem.origType = fileVar.type; // unnecessary for loading the image, used by a current project.
}
}
function onFileChosen(evt)
{
if (this.files.length != 0)
{
var tgtImg = byId('tgt');
var curFile = this.files[0];
loadImgFromFile(curFile, tgtImg);
}
}
</script>
<style>
</style>
</head>
<body>
<input id='mFileInput' type='file'/><br>
<img id='tgt' />
</body>
</html>

How can i display image preview in HTML file field [duplicate]

In my HTML form I have input filed with type file for example :
<input type="file" multiple>
Then I'm selecting multiple files by clicking that input button.
Now I want to show preview of selected images before submitting form . How to do that in HTML 5?
Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:
The html code:
<input accept="image/*" type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById('files').onchange = function () {
var src = URL.createObjectURL(this.files[0])
document.getElementById('image').src = src
}
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect (evt) {
// Loop through the FileList and render image files as thumbnails.
for (const file of evt.target.files) {
// Render thumbnail.
const span = document.createElement('span')
const src = URL.createObjectURL(file)
span.innerHTML =
`<img style="height: 75px; border: 1px solid #000; margin: 5px"` +
`src="${src}" title="${escape(file.name)}">`
document.getElementById('list').insertBefore(span, null)
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>
Here I did with jQuery using FileReader API.
Html Markup:
<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>
jQuery:
Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[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($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
function handleFileSelect(evt) {
var files = evt.target.files;
// 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 style="height: 75px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>
For background images, make sure to use url()
node.backgroundImage = 'url(' + e.target.result + ')';
Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).
Don't forget to validate image extension.
<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');
const handle_file_preview = (e) => {
let files = e.target.files;
let length = files.length;
for(let i = 0; i < length; i++) {
let image = document.createElement('img');
// use the DOMstring for source
image.src = window.URL.createObjectURL(files[i]);
image_preview.appendChild(image);
}
}
file_input.addEventListener('change', handle_file_preview);

Categories