I want to remove files from object - javascript

I created a multiple file upload form. And it shows me the list of files I'm about to upload once I've selected the files. and i made delete file button to remove files that have been deleted from the object but cannot be deleted
<input type="file" class="" id="fileInput" multiple onchange="displayFiles()" style="width: 85px">
function removeFile(index) {
var input = document.getElementById("fileInput");
Array.from(input.files).splice(index, 1);
displayFiles();
}
I tried this method and it didn't work.
function removeFile(index) {
var input = document.getElementById("fileInput");
delete input.files[index];
displayFiles();
}
please help me

Hopefully this small example helps, you could create an array of indices to skip which are used when uploading.
const get = str => document.querySelector(str);
get("#myFiles").addEventListener("change", e => {
get("#howMany").setAttribute("max", e.target.files.length);
});
get("#upload").addEventListener("click", () => {
const files = get("#myFiles").files;
const len = get("#howMany").value;
const data = new FormData();
for (let i = 0; i < len; i++) {
const targetFile = files[i];
data.append("files[]", targetFile, targetFile.name);
}
devFetch("testurl", {
method: "POST",
body: data
});
});
/* DEV FETCH EMULATE NORMAL FETCH FOR STACK SNIPPET, SHOULD JUST BE FETCH */
function devFetch(url, options) {
console.log("Posting to", url, "with method", options.method);
console.log("Body:");
console.log(options.body.getAll("files[]"));
}
<input id="myFiles" type="file" multiple /> <br />
<input id="howMany" type="range" min=0 max=0 /> <br />
<button id="upload">upload</button>

Related

How clear the form inputs after submission?

Already tried everything from different references but, I can't get it to work. I intended to use it for google photo submission form. I just want my text inputs and textarea to clear after it successfully uploaded everything.
Here's the whole HTML code.
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection"
placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = 'xxxxxxxxxxxxxxxxxxx';
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var gradesection = document.getElementById('gradesection').value;
if (!gradesection) {
window.alert('Missing Grade & Section!');
}
var folderName = applicantName + ' - ' + gradesection;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
The form upload and displays the response to the user.
I want to reset the form so, the form resets to its original state, so when the user upload another file it wont upload the same file again. Right now, the submission message stays and I have no clue on how to reset the form.
I am new to javascript and I have no clue on what to call to rest the form, any idea? TIA Guys :)
As your code snippet only contains input, You can find all inputs using querySelectorAll and reset its value.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
You can assign null value to your input element:
const reset = () => {
let fileInput = document.getElementById('file-input');
fileInput.value = null;
}
<input type="file" id="file-input">
<button onclick="reset()">Reset</button>

Vue js : post file to api

i have code below in vue js and i wanted to share a file as u can see, but my problem is i want to save that file name that i uploaded to the API json in post method , is there a way to do it and thanks in advance
<div class="input-file">
<input class="input-file__input" ref="file" type="file">
<div class="input-file__button" #click="selectFile()"></div>
</div>
<script>
selectFile(){
let fileInputElement = this.$refs.file;
fileInputElement.click(); //i want to send this file name to api post method
// ...
},
</script>
Assume that you have an input with 'upload' id, then:
log_file_name() {
const path = document.getElementById('upload').value;
if (path) {
let startIndex = (path.indexOf('\\') >= 0 ? path.lastIndexOf('\\') : path.lastIndexOf('/'));
let filename = path.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
console.log(filename);
}
}
<input class="input-file__input" id="upload" #change="log_file_name()" ref="file" type="file">
You can try to subscribe to change event in order to get a selected file:
<input class="input-file__input" ref="file" type="file" #change="changeFile">
changeFile(event) {
const file = event.target.files[0]
}

Unable to pass Checkbox values to a database

I am building a simple form with text fields as well as an image upload and checkbox options.
I need people to be able to select multiple checkboxes, and those need to be passed to a database.
All the form fields are passing to the database with no issue, except for the Videos(checkbox) field.
Because of the nature of the form, I am required to use client side javascript to pass the form fields via json to SSJS.
At this point, the checkbox values do post to the console log, but they do not make their way to the database. Any help will be much appreciated.
var btn = document.getElementById("button");
btn.addEventListener("click", function() {
var files = document.getElementById("file").files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getChcked() {
var form = document.getElementById('myform');
var chks = form.querySelectorAll('input[type="checkbox"]');
var checked = [];
for(var i = 0; i < chks.length; i++){
if(chks[i].checked){
checked.push(chks[i].value)
}
}
return checked;
};
var Videos = '';
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
//prepare data to pass to processing page
var fileEncoded = reader.result;
var base64enc = fileEncoded.split(";base64,")[1];
var fullFileName = document.getElementById("file").files[0].name;
var fileName = fullFileName.split(".")[0];
var assetName = fullFileName.split(".")[1];
var AgencyName = document.getElementById("AgencyName").value;
var AgencyPhone = document.getElementById("AgencyPhone").value;
var AgencyEmail = document.getElementById("AgencyEmail").value;
var AgencyWebsite = document.getElementById("AgencyWebsite").value;
var Videos = console.log(getChcked());
fetch("processingpage", { //provide URL of the processing page
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
base64enc: base64enc,
fileName: fileName,
assetName: assetName,
AgencyName: AgencyName,
AgencyPhone: AgencyPhone,
AgencyEmail: AgencyEmail,
AgencyWebsite: AgencyWebsite,
Videos: Videos
})
});
};
}
<div class="form-group">
<label class="col-md-4 control-label" for="Videos">Select which video(s) you’d like co-branded:</label>
<div class="col-md-4">
<div class="checkbox">
<label for="Videos-0">
<input type="checkbox" name="Videos" id="Videos-0" value="The Flour Child">
The Flour Child
</label>
</div>
<div class="checkbox">
<label for="Videos-1">
<input type="checkbox" name="Videos" id="Videos-1" value="The Loose Tooth Situation">
The Loose Tooth Situation
</label>
</div>
console.log returns undefined, so you are assigning undefined to Videos
var Videos = console.log(getChcked()); // equivalent to var Videos=undefined;

How do I upload multiple files using Firebase?

$("#fileButton1, #fileButton2, #fileButton3").on("change", function(event) {
selectedFile = event.target.files[0];
});
function uploadFile() {
var filename = selectedFile.name;
var storageRef = firebase.storage().ref('/files_new/' + filename);
var uploadTask = storageRef.put(selectedFile);
uploadTask.on('state_changed', function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
}, function () {
window.location.href = "uploadThumbnail.html";
});
}
<form class="upload-form">
<progress value="0" max="100" id="uploader">0%</progress>
<input value="upload" id="fileButton1" class="choose-file-btn" type="file">
<input value="upload" id="fileButton2" class="choose-file-btn" type="file">
<input value="upload" id="fileButton3" class="choose-file-btn" type="file">
<button type="button" class="submit-btn" onclick="uploadFile()">Continue</button>
</form>
The code above uploads only one file even though I select multiple. How can I make it to push all
files that are selected.
As per the comments i understood you want multiple input files and you want to send all at a time
Follow this and play with your requirement by keeping the below code as reference
$(document).ready(function(){
var filesList = [],
paramNames = [],
elem = $("form");
file_upload = elem.fileupload({
formData:{extra:1},
autoUpload: false,
fileInput: $("input:file"),
}).on("fileuploadadd", function(e, data){
filesList.push(data.files[0]);
paramNames.push(e.delegatedEvent.target.name);
});
$("button").click(function(e){
e.preventDefault();
file_upload.fileupload('send', {files:filesList, paramName: paramNames});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/echo/json/" method="POST">
<input name="file1[]" type="file" multiple />
<br /> <br />
<input name="file2[]" type="file" multiple />
<br /> <br />
<input name="file3[]" type="file" multiple />
<br /> <br />
<button>send by fileupload send api</button>
</form>
You can choose multi files in one input file here
You can save all of the selected files to an array before uploading:
var selectedFiles = [];
$("#fileButton1, #fileButton2, #fileButton3").on("change", function(event) {
var id = $(this).prop('id');
var item = selectedFiles.find(x => x.id === id);
if (!item) {
// if the array doesn't contain any file with this id
// try to push an object which contains id and the file to the array
selectedFiles.push({
id: id,
file: event.target.files[0]
});
} else {
// if the array already contains some file with this id
// try to update the file
item.file = event.target.files[0];
}
});
function uploadFile() {
// uploading file one-by-one
for (var item of selectedFiles) {
var filename = item.file.name;
var storageRef = firebase.storage().ref('/files_new/' + filename);
var uploadTask = storageRef.put(item.file);
uploadTask.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
}, function() {
window.location.href = "uploadThumbnail.html";
});
}
}

drag and drop post multiples files

I would like to create a form with drag and drop functionality.
I see filelist is a read-only object and it's and it's not used with drag and drop. So I copy the file into an array and pass it to my form with formdata. But It doesn't work.
Any ideas?
html :
<form id="upload" action="action.php" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>HTML File Upload</legend>
<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="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
</fieldset>
</form>
<button id="submitbutton" >Upload Files</button>
<div id="messages">
<p>Status Messages</p>
</div>
a reduce of javascript :
var myfiles = [];
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// 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++) {
myfiles.push(f);
ParseFile(f);
}
}
$id("submitbutton").onclick = function(){
var xhr = new XMLHttpRequest();
formData = new FormData(document.querySelector('form'));
xhr.open('get','action.php');
formData.append("files", myfiles);
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(formData);
}
You must append files to FormData one at a time. The syntax used is similar to what you do in your input element and looks like an array. So append your files like this:
myfiles.forEach(file=>{
formData.append("files[]", file);
});
Then, on the server side they will be available in the files array.

Categories

Resources