dynamically delete the attachment? - javascript

I have a form that upload a file..
<form enctype="multipart/form-data" name="" action="" method="POST">
<input type="file" name="file[]" id="files" multiple />
<div id="selectedFiles"></div>
<form>
And a javascript function to display the name and size.
<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;
for(var i=0; i<files.length; i++) {
var f = files[i];
selDiv.innerHTML += "<span class='attach'>" + f.name + " <" + f.size + " bytes>" + "</span>";
}
}
</script>
is their anyone know how to make a delete function on the attachment??
example:
the image shows the uploaded file.. and the red "x" is the delete...
can anyone please help me with this? using javascript..

See comments below.
<form action="some.php" method="post" id="form">
<input type="file" id="file" multiple style="display: none;" />
<button type="button" id="button">Select files</button>
<div id="selectedFiles"></div>
<button type="submit" id="submit">Upload</button>
<form>
var selDiv = document.querySelector("#selectedFiles");
document.querySelector("#button").addEventListener("click", function() {
document.querySelector("#file").click();
}, false);
document.querySelector("#file").addEventListener("change", function() {
var files = this.files;
for (var i = 0; i < files.length; ++i) {
var file = files[i],
span = document.createElement("span");
span.className = "attach";
span.innerHTML = file.name+" <"+file.size+" bytes>";
span.file = file;
var remove = document.createElement("span");
remove.innerHTML = "Remove";
span.appendChild(remove);
selDiv.appendChild(span);
remove.addEventListener("click", function() {
this.parentNode.removeChild(this);
}, false);
}
}, false);
document.querySelector("#form").addEventListener("submit", function(e) {
var files = selDiv.querySelectorAll("span.attach"),
data = new FormData(),
xmlhttp = new XMLHttpRequest();
for (var i = 0; i < files.length; ++i) {
data.append("file[]", files[i].file);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
selDiv.innerHTML = "Uploading completed!";
}
}
xmlhttp.open("POST", "upload.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
return false;
}, false);

Related

How to allow multiple images being upload at once in JS?

I have a form that allow multiple images being upload. But when check at the console. only first image is being shown in console.
console.log C:\fakepath\avatar.jpg
HTML
<form name="addListingForm" id="addListingForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadImage" id="uploadImage" accept="image/*" multiple="" onChange="makeFileList();">
<div id="fileList">No Image Selected</div>
</form>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>
JS
$("#btnUpload").on("click",function(){
var uploadImage = $("#uploadImage").val();
var fd = new FormData();
var files = $('#uploadImage')[0].files[0];
fd.append('file',files);
console.log(files)
var params = JSON.stringify(files);
$.ajax({
// The Image will be upload using ajax tp DB
});
});
function makeFileList() {
var input = document.getElementById("uploadImage");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if (!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Image Selected';
ul.appendChild(li);
}
}
$("#btnUpload").on("click", function() {
var uploadImage = $("#uploadImage").val();
var files = $('#uploadImage')[0].files;
var promises = uploadImages(files);
$.when(...promises).done(function(...args) {
//handle the resulting data here which is an array containing the data
console.log(args)
})
});
function uploadImages(files) {
return $.map(files, function(file) {
var formdata = new FormData();
formdata.append("image", file, file.name);
var settings = {
"url": "https://api.imgbb.com/1/upload?key=516c7e69e9c260a2a00eacceafdb1d62",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": formdata
};
return $.ajax(settings).then(function(res) {
var result = JSON.parse(res)
return result.data.url
})
})
}
function makeFileList() {
var input = document.getElementById("uploadImage");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if (!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Image Selected';
ul.appendChild(li);
}
}
<form name="addListingForm" id="addListingForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploadImage" id="uploadImage" accept="image/*" multiple="" onChange="makeFileList();">
<div id="fileList">No Image Selected</div>
</form>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>

how to upload multiple image in php using javascript array

i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.
This is my javascript
<script type="text/javascript">
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
//console.log(files);
var filePath = $(this).val();
//console.log("fake pathddddddddddd"+filePath);
for (var i = 0; i < filesLength; i++) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = files[i];
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
</script>
dict is my array how can assign that array in php and upload in file,
you can check in console to gat the value
php file
<!DOCTYPE html>
<head>
<style>
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;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
whenever click the clickMe button you can the file name and file path in console check it and please help me
Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to #Ben_Lee with his answer I managed to wrap the initiation inside a function.
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
function initiateFiles(file) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = file;
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
//var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
var filePath = $(this).val();
for (var i = 0; i < filesLength; i++) {
initiateFiles(files[i]);
}
console.log(arrImgNPath);
var myJSON = JSON.stringify(arrImgNPath);
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
});
} else {
alert("Your browser doesn't support to File API");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
Here i created a hidden input, which stores the array.
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
And then assigned an action to the form to send the data to another php file.
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
And now it is time to get the data and process:
<?php
$data = json_decode($_POST['myJSON']);
foreach ($data as $key => $value) {
echo " Name : $value->name <hr>";
echo " Path : $value->path <hr>";
echo " ID : $value->ID <hr>";
}
?>
I hope this helps, if you have further questions, don't hesitate to ask.

what's wrong with these code? why it not sort preview image upload?

Here is the full code for html5 multiple upload file with removeable and preview image
but I don't know in function handleFileSelect(e) why it show the preview images with wrong sorting when choose more than 2 files? (Although, it upload to my folder correctly sort but I still want it to show preview with correct sorting)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
}
.delete_img{
cursor:pointer;
color:red;
font-size:14px;
margin-left:10px;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".delete_img", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
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'> <span class='delete_img'> DEL </span><br>" + f.name + "<br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var username = document.getElementById('username').value; //get value จาก form input
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username); //มาใส่ในajax object formdata เพื่อเตรียมส่งเข้าฝั่งserver
data.append('email', email);
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]); //อย่าลืม []
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
//alert(e.currentTarget.responseText + ' items uploaded.');
window.location = "http://www.google.com";
}
}
xhr.send(data);
}
function removeFile(e) {
var img = e.target.parentElement.querySelector("img")
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
Maybe the total upload size of your files overcomes the max_upload_limit.Usually is 2 MB.As i tested your code in liveweave i don't have problem (5 images).Check the total size of your files. How much is it?

How to upload multiple files through one upload button

When I am executing it not all of my files are uploaded but just one of them.
JavaScript
function upload() {
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[0];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
parseContents(contents);
//document.getElementById("cont").innerHTML=fileContent;
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+myfile.name;
}
r.readAsText(myfile);
}
HTML
<body onload="initialize()">
<div id="container1"><h>MY TRANSIT PLANNER</h></div>
<h3 style="text-decoration:underline;">choose a file for input:</h3>
<input type="file" id="fileinput" multiple="multiple"onchange="upload()"/>
<br>
<div style="color: black" id="uploading"></div>
<script src="https://maps.googleapis.com/maps/api/js?"async defer></script>
<input type="button" id="btn-sgtd" type="text" value="SAVE GTD" onclick="writetofile()"/>
<h3 style="text-decoration:underline;">Choose files to Segment: </h3>
<form action="files.php" method="POST" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple"><br>
<br>
<input type="submit" value="SEGMENT" class="button"><br>
</form>
<div id="map"></div>
</body>
you should do loop
function upload() {
for (var i = 0; i < document.getElementById("fileinput").files.length; i++)
{
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[i];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e)
{
var contents = e.target.result;
parseContents(contents);
//document.getElementById("cont").innerHTML=fileContent;
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+myfile.name;
}
r.readAsText(myfile);
}
}
try this will help you
function upload() {
document.getElementById("uploading").innerHTML="uploading....";
var myfile=document.getElementById("fileinput").files[0];
//alert(myfile.size);
var r = new FileReader();
r.onload = function(e) {
if(!e.target.files) return;
var files = e.target.files;
for(var i=0; i < files.length; i++) {
var f = files[i];
document.getElementById("uploading").innerHTML="<h3>File uploaded: "+f;
}
}

Php is not working with ajax

html code
<form method="post" name="file_upload" enctype="multipart/form-data" id="file_upload">
<input type="file" id="_file" name="_file"> <br>
<input type="button" id="button" value="upload"/> <br>
<progress id="p_bar" value="0" max="100" style="width:300px;"> </progress>
</form>
<p id="status"> </p>
<script src="final.js" > </script>
js
var sfile = document.getElementById('_file') ;
var btn = document.getElementById('button') ;
var f_upload= document.getElementById('file_upload') ;
var pbar = document.getElementById('p_bar') ;
var sbar = document.getElementById('status') ;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ") ;
}
var s_file = sfile.files[0] ;
var formdata = new FormData () ;
formdata.append( 'selected file ',s_file) ;
var ajax = new XMLHttpRequest () ;
ajax.upload.addEventListener("progress", progress , false ) ;
function progress (event) {
var percent = (event.loaded / event.total) * 100 ;
pbar.value = Math.round(percent) ;
sbar.innerHTML = Math.round(percent)+"%.........uploaded" ;
}
ajax.open("POST", "final.php") ;
ajax.send(formdata) ;
}
btn.addEventListener("click", upload , false ) ;`
PHP
<?php
$file_name = $_FILES['_file']['name'] ;
$file_temp = $_FILES['_file']['tmp_name'] ;
$file_size = $_FILES['_file']['size'] ;
$file_type = $_FILES['_file']['type'] ;
$file_error = $_FILES['_file']['size'] ;
$file_destination = "upload/".basename($file_name) ;
if( move_uploaded_file($file_temp, $file_destination) ) {
echo "file uploaded" ;
}
else {
echo " file is failed to upload " ;
}
In these no working on php . if i only put echo still not output in main page . also if in php we caught with name tag in html than why use of send function in ajax.like ajax.send(formdata)
the problem here is you are not looking for ajax response.try this:
<script>
var sfile = document.getElementById('_file');
var btn = document.getElementById('button');
var f_upload= document.getElementById('file_upload');
var pbar = document.getElementById('p_bar');
var sbar = document.getElementById('status');
var ajax = null;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ");
return;
}
var s_file = sfile.files[0];
var formdata = new FormData();
formdata.append('_file',s_file);//your key is _file
ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progress , false);
ajax.open("POST", "final.php");
ajax.onreadystatechange = OnStateChange;
ajax.send(formdata);
}
btn.addEventListener("click", upload , false);
function progress (event) {
var percent = (event.loaded / event.total) * 100;
pbar.value = Math.round(percent);
sbar.innerHTML = Math.round(percent)+"%.........uploaded";
}
function OnStateChange () {
if (ajax.readyState == 4 && ajax.status == 200) {
var resp = ajax.responseText;
alert(resp);
}
}
</script>

Categories

Resources