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

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>

Related

How to call a javascript function?

I try to call a js function from a razor-file. The script is available in index.html. The number of selected files will be shown. But I expect under the html-text: "Selected files:" the names of the Excel-files. But after selecting nothing is shown.
What do I wrong? And do I solve it?
The blazor-page [importexceldata.razor]
#page "/importexceldata"
#inject IJSRuntime js
<h3>Import Excel Data</h3>
<form>
<div><input id="minimum" type="text" /></div>
<div><input id="maximum" type="text" /></div>
<div></div>
<div></div>
<p><span>Select file(s) to upload :</span></p>
<p>
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
onchange="javascript:updateList()" />
</p>
<p>
<input class="btn btn-warning"
id="button1"
type="button"
value="Upload" />
</p>
<p>Selected files:</p>
<div id="fileList"></div>
</form>
#code {
public object UpdateList() => js.InvokeAsync<object>("updateList");
//protected override async Task OnAfterRenderAsync(bool firstRender)
//{
//}
}
... and the index.html
<script type="text/javascript">
window.document.readyState(function(){
$("#button1").click(function (evt) {
var files = $("#file").get(0).files;
var minimum = $("#minimum").val();
var maximum = $("#maximum").val();
if (files.length > 0) {
console.log(files.length);
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
console.log(data);
$.ajax({
type: "POST",
url: "/Home/UploadFiles?minimum=" + minimum + "&maximum=" + maximum,
contentType: false,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
alert(messages[i]);
}
},
error: function () {
alert("Error while invoking the Web API");
}
});
}
});
//window.jsMethod = (updateList) => {
updateList = function () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
</script>
</body>
</html>
Check your function code, There is no return value, So you can't call js like this:
#code {
public object UpdateList() => js.InvokeAsync<object>("updateList");
}
Change your function code like this:
function updateList () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
Change input code use #onchange=xx:
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
#onchange="UpdateList" />
Then call js like this:
#code {
public async Task UpdateList() {
await Js.InvokeVoidAsync("updateList");
}
}
Demo
==================Edit===============
#page "/importexceldata"
#inject IJSRuntime Js
<PageTitle>Index</PageTitle>
<form>
<div><input id="minimum" type="text" /></div>
<div><input id="maximum" type="text" /></div>
<div></div>
<div></div>
<p><span>Select file(s) to upload :</span></p>
<p>
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
#onchange="UpdateList" />
</p>
<p>
<input class="btn btn-warning"
id="button1"
type="button"
value="Upload" />
</p>
<p>Selected files:</p>
<div id="fileList"></div>
</form>
#code {
public async Task UpdateList() {
await Js.InvokeVoidAsync("updateList");
}
}
Index
<script type="text/javascript">
$(document).ready(function () {
$("#button1").click(function (evt) {
var files = $("#file").get(0).files;
var minimum = $("#minimum").val();
var maximum = $("#maximum").val();
if (files.length > 0) {
console.log(files.length);
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
console.log(data);
$.ajax({
type: "POST",
url: "/Home/UploadFiles?minimum=" + minimum + "&maximum=" + maximum,
contentType: false,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
alert(messages[i]);
}
},
error: function () {
alert("Error while invoking the Web API");
}
});
}
});
});
//window.jsMethod = (updateList) => {
function updateList () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
</script>

File not found exception when trying to get drag and drop image in java

My code as follows
<script>
var formData = new FormData();
var doc = document.documentElement;
var files;
doc.ondragover = function () {
this.className = 'hover';
document.getElementById("image-div").style.border = "dotted";
return false;
};
doc.ondragend = function () {
document.getElementById("image-div").style.border = "solid";
this.className = '';
return false;
};
doc.ondrop = function (event) {
document.getElementById("image-div").style.border = "solid";
event.preventDefault && event.preventDefault();
this.className = '';
files = event.dataTransfer.files[0];
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
var fileReader = new FileReader();
fileReader.onload = function (event)
{
document.getElementById("previewImg").src = event.target.result;
}
fileReader.readAsDataURL(files);
return false;
};
jQuery.ajax({
url: 'URL',
data: formData,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
</script>
<body>
<form class="box" method="post" action="URL" id='SubmitForm' enctype="multipart/form-data">
<div class="image" style="border-style: solid;border-color: yellow;height: 300px;width: 300px;text-align: center;margin: 10px" id="image-div">
<p><label for="file"><strong>Choose a file</strong></label><span class="hide" id="drag"> or drag it here</span>.</p>
</div>
<div id="previewImage" style="display:none;border:1px solid black">
<img src="#" id="previewImg" style="width:250px;height:auto">
</div>
<div>
<input type='file' class="inputfile" name='file' id="file" accept='image/*' />
<input type='submit' value='Upload' name='Upload image' />
</div>
</form>
</body>
Exception at this line
InputStream fileContent = formFile.getInputStream();
Exception:
java.lang.RuntimeException: java.io.FileNotFoundException:
C:\Windows\TEMP\upload_723aa03a_1e6b_457a_b020_b33fc078881b_00000001.tmp
(The system cannot find the file specified)

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?

dynamically delete the attachment?

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

Cannot get file type input to clear

So i've looked at the other questions and I am too far along in my page to try something else. I have an input type of file and I am trying to clear it when the user decides that they do not want to use it. I have some other functionality that is set to show the file name, size, etc... based on the FILE API but for some reason I cannot get the input to clear. I am trying a few different ways to clear it but still nothing. Anyone see what I am doing wrong. I have a jQuery check to check the value of the input and it never clears. The only thing I can think of is that I am using the standard hide the input and using a link so I can actually style the file input button.
Here is the FIDDLE:
JS FIDDLE
Here is the HTML:
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
onchange="handleFiles(this.files)" name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
Here is the script:
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
};
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
I Corrected It this is the answer Try this....
The problem you are facing is this error...
Uncaught ReferenceError: handleFiles is not defined
So I canged it like this...
HTML
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
</div>
SCRIPT
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$("#fileElem").change(function() {
var files=this.files;
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
});
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
JSFIDDLE LINK HERE
This is the Link for updated JSFIDDLE...

Categories

Resources