How to upload multiple files through one upload button - javascript

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

Related

Problem with Upload file to Google Drive using google script

I used these AttachFileFromJS() before and it work properly but that is in webapp deployment
,but this code has error when run inside modal on google sheet
(I'm not quite sure that make any difference?)
Code.gs
function UploadToDrive(){
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutputFromFile('Upload').setWidth(400).setHeight(300);
ui.showModelessDialog(html," ");
}
function AttachFileFromJS(folderId,fileObj){
var folder = DriveApp.getFolderById(folderId);
if(fileObj.fileName != ''){
var data = Utilities.base64Decode(fileObj.fileData);
var blob = Utilities.newBlob(data, fileObj.mimeType, fileObj.fileName);
var createFile = folder.createFile(blob);
var picId = createFile.getId() ;
return picId ;
}
}
function Uploader(fileObj){
var folderId = '1VaRzewFKEUWL3DJ_uf7z6lIocFqu0P6j';
AttachFileFromJS(folderId,fileObj)
}
Upload.html (show only some part)
<div id="attach" name="attach">
<input type="file" name="file" id="fileInput" onchange="LoadFile(event)" />
<input type="hidden" id="fileData" name="fileData" />
<input type="hidden" id="mimeType" name="mimeType" />
<input type="hidden" id="fileName" name="fileName" />
</div><br>
<div class="form-group">
<button type="button" class="form-control btn btn-primary rounded submit px-3" onclick="UploadFile()" >Upload File</button>
</div>
Javascript
function LoadFile(event)
{
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
var fileData = e.target.result.substr(e.target.result.indexOf(",")+1);
var mimeTypeStart = e.target.result.indexOf("data:") + 5;
var mimeTypeEnd = e.target.result.indexOf(";");
var mimeType = e.target.result.substr(mimeTypeStart, mimeTypeEnd - mimeTypeStart);
var fileName = file.name;
document.getElementById("fileData").value = fileData;
document.getElementById("mimeType").value = mimeType;
document.getElementById("fileName").value = fileName;
};
reader.readAsDataURL(file);
}
function UploadFile(){
var File1 = {};
File1.fileData = document.getElementById("fileData").value ;
File1.mimeType = document.getElementById("mimeType").value ;
File1.fileName = document.getElementById("fileName").value ;
google.script.run.Uploader(File1) ;
}

Not removing value from multifile

I'm running the following to upload and remove any file if clicked:
$(document).on('click','.close',function(){
$(this).parents('span').remove();
})
document.getElementById("usp-files").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
document.getElementById('usp-files').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#usp-files')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>'+files[i].name+'<p class="close">X</p></span>');
}
document.getElementById('filename').value = filename;
}
HTML
<input type="hidden" id="uploadFile" placeholder="Add files from My Computer" class="steptextboxq3"/>
<div class="fileUpload btn btn-primary">
<span>Browse</span>
<input name="usp-files[]" id="usp-files" type="file" maxlength="999999" data-required="false" placeholder="Upload your images here" class="upload sp-input usp-input-files my_images select-file multiple" multiple="multiple" name="browsefile">
</div>
<input id="filename" type="hidden" />
<div id="upload_prev"></div>
Visually, we can see that it is removing it, but when I then send it to the server, it is saving all the files I have uploaded even tho I have removed them in front end.
jsFiddle here

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

Categories

Resources