Javascript - How to delete selected picture? - javascript

This is the code, so here is code for multiple preview images. So I want to delete the selected image? So when you upload images you click on image and image disappeared but it's only hidden not deleted?
How I can fix this? Because I'm using .remove(); method but nothings happened, its just hidden image
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
var selDiv = "";
var storedFiles = [];
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var device = $(e.target).data("device");
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function(e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='" + f.name + "' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
$("#selectedFiles").append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for (var i = 0, len = storedFiles.length; i < len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.cfm', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
}
This is my simple HTML
<script src="aa.js"></script>
<form id="myForm">
<input type="file" id="files" name="files" multiple>
<div id="selectedFiles"></div>
<br/>
<input type="submit">
</form>

You need to reset the input value:
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
// add it here
jQuery("#files").val("");
}

Related

Browser getting stuck to upload large files

I am using basic javascript and trying to upload a file appx 500Mb, but my browser is getting stuck. Below is my javascript code
main.js
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
var multipleUploadForm = document.querySelector('#multipleUploadForm');
var multipleFileUploadInput = document.querySelector('#multipleFileUploadInput');
var multipleFileUploadError = document.querySelector('#multipleFileUploadError');
var multipleFileUploadSuccess = document.querySelector('#multipleFileUploadSuccess');
var asyncMltipleUploadForm = document.querySelector('#asyncMltipleUploadForm');
var asyncMultipleFileUploadInput = document.querySelector('#asyncMltipleUploadInput');
var asyncMultipleFileUploadError = document.querySelector('#asyncMultipleFileUploadError');
var asyncMultipleFileUploadSuccess = document.querySelector('#asyncMultipleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
// singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
function resolveAfter2Seconds(file) {
return new Promise(resolve => {
// setTimeout(() => {
resolve(uploadSingleFile(file));
// }, null);
} );
}
async function asynchUploadMultipleFiles(files) {
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
// formData.append("files", files[index]);
var startDate = new Date();
await resolveAfter2Seconds(files[index]);
var endDate = new Date();
var diff = endDate - startDate;
asyncMultipleFileUploadSuccess.innerHTML = "time taken :::: " + diff;
asyncMultipleFileUploadSuccess.style.display = "block";
}
}
function uploadMultipleFiles(files) {
var startDate = new Date();
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
formData.append("files", files[index]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadMultipleFiles");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
multipleFileUploadError.style.display = "none";
var content = "<p>All Files Uploaded Successfully</p>";
// for(var i = 0; i < response.length; i++) {
// content += "<p>DownloadUrl : <a href='" + response[i].fileDownloadUri + "' target='_blank'>" + response[i].fileDownloadUri + "</a></p>";
// }
var endDate = new Date();
var diff = endDate - startDate;
multipleFileUploadSuccess.innerHTML = content + "time taken :::: " + diff;
multipleFileUploadSuccess.style.display = "block";
} else {
multipleFileUploadSuccess.style.display = "none";
multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
// console.log(xhr.responseText);
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
multipleUploadForm.addEventListener('submit', function(event){
var files = multipleFileUploadInput.files;
if(files.length === 0) {
multipleFileUploadError.innerHTML = "Please select at least one file";
multipleFileUploadError.style.display = "block";
}
uploadMultipleFiles(files);
event.preventDefault();
}, true);
asyncMltipleUploadForm.addEventListener('submit', function(event){
var files = asyncMultipleFileUploadInput.files;
if(files.length === 0) {
asyncMultipleFileUploadError.innerHTML = "Please select at least one file";
asyncMultipleFileUploadError.style.display = "block";
}
asynchUploadMultipleFiles(files);
event.preventDefault();
}, true);
Can you please help

How to dynamically load photos to dynamically loaded divs?

I wrote this code, which creates divs depending on the amount of text files in local directory.
Then I tried to write additional code, which appends photos to each of these divs. Unfortunately, this code doesn't append any photos...
function liGenerator() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var n = (xmlhttp.responseText.match(/txt/g) || []).length;
for (var i = 1; i < n; i++) {
$.get("projects/txt/"+i+".txt", function(data) {
var line = data.split('\n');
var num = line[0]-"\n";
var clss = line[1];
var title = line[2];
var price = line[3];
var content = line[4];
$("#list-portfolio").append("<li class='item "+clss+" show' onclick='productSelection('"+num+"')'><img src='projects/src/"+num+"/title.jpg'/><div class='title'><h1>"+title+"</h1><h2>"+price+"</h2></div><article>"+content+"</article></li>");
$("#full-size-articles").append("<li class='product "+num+"'><div><div class='photo_gallery'><div id='fsa_img "+num+"'><div width='100%' class='firstgalleryitem'></div></div></div><article class='content'><h1 class='header_article'>"+title+"</h1><h2 class='price_article'>"+price+"</h2><section class='section_article'>"+content+"</section></article></div></li>");
});
}
}
}
};
xmlhttp.open("GET", "projects/txt/", true);
xmlhttp.send();
}
function pushPhotos() {
var list = document.getElementById("full-size-articles").getElementsByTagName("li");
var amount = list.length;
for(var i=1;i<=amount;i++) {
var divID = "#fsa_img "+i;
var where = "projects/src/"+i+"/";
var fx = ".jpg";
loadPhotos(where, fx, divID);
}
}
function loadPhotos(dir, fileextension, div) {
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location, "").replace("http://", "");
$(div).append("<img src='"+dir+filename+"' class='mini_photo'/>");
});
}
});
}
Any ideas on why this code is not working as intended?
The main issue is the space between "#fsa_img" and "i". When I changed it to '"#fsa_img_"+i', the code started work as intended.

How to submit all the uploaded files at once via AJAX vs submitting it one by one?

The code below submits file on drop and will call ajaxat the same time but I tried changing it to a way where user can drop files after files and submit it at once.
I wrapped the function that sends file to ajaxwith on click but it is still sending file one by one. Why?
function handleFileUpload(files, obj) {
for (var i = 0; i < files.length; i++) {
var fd = new FormData();
fd.append('file', files[i]);
var status = new createStatusbar(obj); //Using this we can set progress.
status.setFileNameSize(files[i].name, files[i].size);
}
var submit = $("#submit-button-id");
submit.on('click', function(e) {
e.preventDefault();
alert("clicked nest!")
sendFileToServer(fd, status);
});
}
And here is the Web API ajaxcall function:
function sendFileToServer(formData, status) {
var uploadURL = _config.UploadPrismaTemplates;
var extraData = {}; //Extra Data.
var jqXHR = $.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType: false, //not to set any content header
processData: false, //not to process data
cache: false,
data: formData,
success: function(data) {
status.setProgress(100);
//$("#status1").append("File upload Done<br>");
alert("set progress success");
},
error: function(xhr, status, error) {
alert(error);
}
});
status.setAbort(jqXHR);
} /*send file to server ends here*/
Here I fixed it ! It will only submit files if clicked.
$(document).ready(function(){
var drop = $('#drag-and-drop-zone');
var uploadBtn = $('#submit-button-id');
drop.on('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
$(this).css('border', '2px solid #0B85A1');
});
drop.on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
});
var rowCount = 0;
function createStatusbar(drop) {
rowCount++;
var row = "odd";
if (rowCount % 2 == 0) row = "even";
this.statusbar = $("<div class='statusbar " + row + "'></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
$('#display-status-id').append(this.statusbar);
this.setFileNameSize = function (name, size) {
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
}
else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
this.filename.html(name);
this.size.html(sizeStr);
}
this.setProgress = function (progress) {
var progressBarWidth = progress * this.progressBar.width() / 100;
this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
if (parseInt(progress) >= 100) {
this.abort.hide();
}
}
this.setAbort = function (jqxhr) {
var sb = this.statusbar;
this.abort.click(function () {
jqxhr.abort();
sb.hide();
});
}
}
/*****************************************/
drop.on('drop', function (e) {
$(this).css('border', '2px dotted #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
if (!files) return;
console.log("drop:", drop);
for (var i = 0; i < files.length; i++) {
var status = new createStatusbar(drop);
status.setFileNameSize(files[i].name, files[i].size);
}
uploadBtn.on('click', function (e) {
var fd = new FormData();
for (var i = 0; i < files.length; i++)
{
fd.append(files[i].name, files[i]);
}
sendFiletoServer(fd);
});
function sendFiletoServer(formData) {
var uploadURL = "";
var extraData = {};
var jqXHR = $.ajax({
xhr: function () {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
Call event.preventDefault() at dragover event of droppable element, use a <button> element for user to click when they want to upload the FormData() object containing the files that they have dropped.
var drop = document.getElementById("drop");
var button = document.getElementById("upload");
var fd = new FormData();
drop.ondragover = function(e) {
e.preventDefault();
}
drop.ondrop = function(e) {
e.preventDefault();
if (e.dataTransfer.types[0] === "Files") {
var file = e.dataTransfer.files[0];
fd.append("files[]", file, file.name);
}
}
button.onclick = function(e) {
console.log([...fd]);
// do ajax stuff with `fd` here
// delete items in `fd` when ajax stuff completes
for (let [key, prop] of [...fd]) {
fd.delete(key)
}
console.log([...fd]);
}
#drop {
width: 300px;
height: 200px;
border: 2px dotted green;
text-align: center;
}
<div id="drop">Drop files</div>
<button id="upload">Upload</button>

Why does my redirect is not working?

my script calls my redirect function to early, so the last file of a batch upload is failing. I have been search the whole morning an tried different approaches, but without success.
function uploadFile(something, callback) {
var fileInput = $('#fileList1');
//var reader = new FileReader();
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var fileList = [];
count = fileInput[0].files.length;
for(i = 0; i < count; i++){
loadFile(fileInput[0].files[i]);
}
function loadFile(file){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
redirect();
}
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
function redirect(){
window.location.href = '/{!tempID}';
return false;
}
Can someone give me a hint?
#
Hello, i have rewritten my methods a bit based on your suggestions. But the redirect is still called to early,...before all uploads are done.
function uploadFile() {
var fileInput = $('#fileList1');
console.log(fileInput);
if ( trim( fileInput.val() ).length == 0 ) {
return;
}
var countTwo = 0;
count = fileInput[0].files.length;
for(var i = 0; i < count; i++){
loadFile(fileInput[0].files[i], function(val){
console.log(val);
if(val === 3){
setTimeout(()=>{redirect();}, 5000);
}
});
}
function loadFile(file, callback){
var reader = new FileReader();
var fileName = getFileNameWithExtension( file);
var file = file;
while(reader.onprogress){
console.log("reading");
}
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
console.log(" ct " + countTwo + " c " + count-1);
countTwo++;
if(!--count) callback(countTwo);
}
reader.onerror = function(event) {
console.error("File could not be read! Code " + reader.error.message);
}
reader.readAsDataURL(file);
}
}
Method 1: (Recommended)
Detect when your uploading ends. And in that callback, call redirect.
Method 2:
// define your TIMEOUT first
setTimeout(()=>{redirect();}, TIMEOUT);
reader.onload = function(event) {
var val = reader.result;
var text = val.split(',')[1];
saveFile( fileName, text, parentId );
if (!--count){
setTimeout(()=>{redirect();}, 0);
}
}

Convert a Fetched data in div from excel to a query

The below code fetches data from a csv and presents in to a div as a text but am trying to convert that in to a query on fetch excel import and print then as a query
Current output when the data is imported from the excel
Example:
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
column1','column2','column3','column4')
Expected output
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4'),
('column1','column2','column3','column4');
JS fiddle demo
HTML:
<input id = "csv" type = "file" />
<div id="result"></div>
JS:
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
var fourColumnsData = lineSplit[j].split(',').slice(0, 4).join("','");
content.push(fourColumnsData);
}
var fileContent = content.join("')<br/>");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
Try the following
$('#csv').change(function(e) {
if ((window.FileReader) && (e.target.files != undefined)) {
var reader = new FileReader();
reader.onload = function(e) {
var lineSplit = e.target.result.split("\n");
var content = [];
for (var j = 1; j < lineSplit.length; j++) {
if (lineSplit[j].trim().length > 0) {
var fourColumnsData = "('" + lineSplit[j].split(',').slice(0, 4).join("','") + "')";
content.push(fourColumnsData);
}
}
var fileContent = content.join(",");
$('#result').html(fileContent);
};
reader.readAsText(e.target.files.item(0));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="csv" type="file" />
<div id="result"></div>

Categories

Resources