Pass filename from file upload to text field - javascript

I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.

Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/

HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}

A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.

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>

How do I rename a file after uploading it?

I have this input type, if I upload a file with less than 8 length add zeros, but what I need is to change my input with the new name.
<body>
<input type="file" id="upload" />
<script>
$(document).ready(function(){
$('#upload').change(function(e){
var fileName = e.target.files[0].name;
var newName = fileName.substring(0,fileName.length-4);
while(newName.length<8){
newName = "0"+newName;
}
console.log(e.target.files[0].name=newName);
});
});
</script>

Assign value to an hidden text input with JS

i'm a newbie of JavaScript.
I have that :
HTML:
<form>
<t:inputFileUpload required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />
<h:commandButton class="btn btn-primary" value="Upload"
action="#{controller.upload}" />
</form>
javascript:
<script>
function uploadOnChange() {
document.getElementById('upload').onchange = name;
var filename = name;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
</script>
All I want to do is get through a inputFileUpload, to browse my directory, the filename that i've selected, and pass this name as a string to jsf controller.
Does anyone can help me?
EDIT :
If I add to my form enctype="multipart/form-data seems that the controller method "upload" does nothing.
Assuming <t:inputFileUpload> has a value attribute, I'd change the code to something like this:
function uploadOnChange() {
var filename = document.getElementById('upload').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
console.log('Value hidden input: ' + document.getElementById('filename').value);
}
<input type="file" required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />

Validate on select while choosing files for upload

I am trying to validate file types as soon as the files are choosen for upload
Below is my html code
<label> <input type="file" id="image" name="upload[]" multiple="multiple" onclick="validateFileExtension()" />
Validation code
function validateFileExtension() {
var ext = $('#my-file-selector').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
alert('invalid extension!');
}
}
But it is not validating as soon as the files are selected. Only upon submitting the form, the validation happens. i have other a jquery for validation on submit. I need to validate on select. Please help out
onclick is not firing after you select a file. using onchange instead works.
function validateFileExtension(element) {
var files = $(element)[0].files;
for(var i = 0; i < files.length; i++) {
var ext = files[i].name.split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
console.log('invalid extension!', ext);
} else {
console.log('valid extension :)', ext);
}
}
}
function validateForm(form) {
validateFileExtension(form.image);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file" id="image" name="upload[]" multiple="multiple" onchange="validateFileExtension(this)" />
<br>
<input type="submit" onclick="validateForm(this.parentNode)" />
</form>
You need to use onchange and need to loop through the files array if using the multiple attribute
function validateFileExtension(element) {
var i;
for (i = 0; i < element.files.length; i++) {
// make sure in all browsers were just looking at the file name
var ext = element.files[i].name.split('.')[1].toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
element.value = ""; // clear the input field
alert('invalid extension!'); // now alert user
}
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>File</label>
<input type="file" id="image" name="upload[]" multiple="multiple" onchange="validateFileExtension(this);" />

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

Categories

Resources