multiple file uploading with other data using ajax - javascript

I want to upload multiple files and store them in a folder and get other data.
html file
<form enctype='multipart/form-data' id='formtest' method='POST' >
<input type='text' name='report_name' id='report_name'/>
<input type='file' id='multiFiles' name='files[]' class='multiupload'
multiple='multiple'/>
<button type='button'>Submit</buton>
js file
var elem = document.getElementsByClassName("files");
var names = [];
for (var i = 0; i < elem.length; i++) {
if(elem[i].value != ''){
names.push(elem[i].value);
}
}
tmpData = new FormData();
tmpData.append('files',form_data);
tmpData.append('report_name',document.getElementById('report_name').value );
AJAX("treatment.php", 0, tmpData);
php file
echo count($_FILES['files']['name']);
I tried this code but this is not working.

var elem = document.getElementsByClassName("files");
In your code, file type input doesn't seem to have "files" class so you can't get it this way. Try
var elem = document.getElementsByClassName("multiupload");
Instead

Related

Get file names for the file upload element [duplicate]

This question already has answers here:
Javascript - How to extract filename from a file input control
(15 answers)
Closed 2 years ago.
Trying to display the file names from a file input element. I am able to console log when I am inside the onchange function but not the addeventlistener. In the code below the console.log('Inside change eventlistener'); will not execute. I can I both log being inside the event listener and get the file names in order to display them? Here is the codepen of the code. Thank you.
html:
<label>Attachments</label>
<div>
<input type="file" class="form-control input-lg" name="attachments" id="attachments" multiple onchange="getFileData()">
</div>
js:
function getFileData() {
console.log('Inside getFileData()...')
var elem = document.getElementById('attachments');
console.log(elem);
elem.addEventListener('change', function(e) {
console.log('Inside change eventlistener');
console.log(e.target);
var fileName = e.target.files[0].name;
console.log(fileName);
});
};
UPDATE:
I am able to console the file names but still not able to display the names to the user. How do I show the names of the files within on the html page. elem.value = ... does not work.
Updated JS:
function getFileData() {
console.log('Inside getFileData()...')
var elem = document.getElementById('attachments');
var files = document.getElementById('attachments').files;
var names = '';
for (let i = 0; i < files.length; i++) {
console.log(files[i].name);
names += files[i].name;
}
console.log(names);
console.log(Object.keys(elem));
//elem.setAttribute('value', names);
};
You may try something like this
var elem = document.getElementById('attachments');
elem.addEventListener('change', getFileData);
function getFileData() {
const files = this.files;
const list = document.getElementById("result");
let child;
for ( let i = 0; i < files.length; i++) {
child = document.createElement("li")
child.textContent = files[i].name;
list.append(child);
}
}
<label>Attachments</label>
<div>
<input type="file" class="form-control input-lg" name="attachments" id="attachments" multiple>
</div>
<ul id="result"></ul>

How to pass an array created in javascript to another jsp and then use that array in a java function on that jsp?

Here is a script i have and I want to be able to pass the array "playernames" into a java function on another .jsp. I'm wonder how to pass that array to another page and then retrieve it for my java function.
<script>
function getPlayerNames() {
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
}
</script>
Edit:
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<input type="hidden" id="players" />
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").values=playernames;
document.getElementById("players").submit();
window.location.replace("lineups.jsp");
}</script>
Other jsp
<%String[] players = request.getParameterValues("players");%>
You'll need to have the hidden field inside the form tags with the id and action attributes set as below.
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<form id="playerNames" action="Url"> // In action give the Url of the jsp page you want to send the values to lineups.jsp in your case I guess.
<input type="hidden" id="players" name="players" />
</form>
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").value=playernames;
document.getElementById("playerNames").submit();
}</script>
1) Stringify the array and then assign to hidden field.
Refer: Javascript Hidden Input Array
2) Submit the hidden field in a form to server.
<input type="hidden" id="hiddenArrayField"/>
document.getElementById("hiddenArrayField").value=yourStringifyArrayValue;
3) On server you would get this as a part of request i.e. on next jsp you can retrieve this value as a request parameter.
<%= request.getParameter("hiddenArrayField")%>

Undefined file in javascript array when grabbing files from an input type="file" tag

I have this really weird issue while grabbing images from an input tag, and I can't figure out why. Here's the code:
var files,
fileCounter = 0,
fileArray = [];
$("#fc").on("change", function() {
files = $("#fc")[0].files;
console.log(files);
for (var i = 0; i < files.length; i++) {
fileArray[fileCounter] = files[fileCounter];
fileCounter++;
console.log(fileArray);
}
});
The html is pretty simple:
<input type="file" id="fc" multiple="multiple" />
The fileArray should be grabbing each image as I add it, but it will only grab 2 before listing files as "undefined". No clue why.
The issue you are having on subsequent additions to fileArray stems from your index value in the assignment:
fileArray[fileCounter] = files[fileCounter];
Because fileCounter is essentially the length of the fileArray, after the first loop any subsequent additions would cause fileCounter to start at values greater than 0. Therefore when you tried to assign files[fileCounter] to the fileArray, the index you were selecting was greater than 0 which for a single file array would mean you were referencing an undefined element.
That said, you don't really need those counters but just the array:
var fileArray = [];
$("#fc").on("change", function() {
var files = $("#fc")[0].files;
console.log(files);
for (var i = 0, len = files.length; i < len; i++) {
fileArray.push(files[i]);
console.log(fileArray);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fc" multiple="multiple" />
You could even simplify this further by using concat and slice:
var fileArray = [];
$("#fc").on("change", function() {
var files = $("#fc")[0].files;
console.log(files);
// convert `files` to an array and concat it to `fileArray`
fileArray = fileArray.concat(Array.prototype.slice.call(files));
console.log(fileArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fc" multiple="multiple" />

Drag and drop zone in JS - File input

I have problem with uploading files in my existing form.
What I am looking for is script that will make possible to add multiple files (max 5) and you can add at once from one to five files. If you add one by one, I need it to add new, not replace the previous one.
I got form looking like this:
Name
LastName
Email
Phone number
Interests
Files
and filenames are created like this: name+lastname+phonenumber+filename
And I add entry to database with path of everyfile - this is done and I need only good drag and drop zone.
I need it to show added filename and make it possible to delete added file from queue.
But I don't want files to upload when I add them. I want it to upload when I submit my whole form so filename can be created and path to DB can be added.
Could anyone please provide me good script to that, or based on my scripts from two topics I mentioned before make it avaiable to do what I want?
I was able to add 5 files one by one and I described it here:
HTML Add multiple file to the input
Also I was able to add more at once what I described here:
https://stackoverflow.com/questions/30499388/dropzone-js-into-another-form
I think that this example help you.
This app allow drag and drop files to gray zone (1 or 5)
If you click on the file name, it removes file from the list.
function init() {
//get dragdrop element
var dd = document.getElementById("dragdrop");
//get files element
$files = document.getElementById("files");
dd.ondragover = stop;
dd.ondragleave = stop;
if ('FileReader' in window) {
document.ondrop = dragAccept;
}
//get form
var $form = document.querySelector("form");
//catch on submit
$form.onsubmit = function (e) {
stop(e);
var fd = new FormData();
//apend files to FormData
for (var i in files){
var file = files[i].file;
var filename = file.name;
var name = "file";
fd.append(name, file, filename);
};
//append inputs to FormData
var $inputs = $form.querySelectorAll("input");
for (var i = 0; i < $inputs.length; i++) {
var $input = $inputs[i];
fd.append($input.getAttribute("name"), $input.value);
}
//Send data
var xhr = new XMLHttpRequest();
xhr.open('POST', '/echo/html/', true);
xhr.send(fd)
}
}
function stop(e) {
e.stopPropagation();
e.preventDefault();
}
function dragAccept(e) {
stop(e);
if (e.dataTransfer.files.length > 0)
for (var i = 0; i < e.dataTransfer.files.length; i++) {
addFile(e.dataTransfer.files[i]);
}
}
//file list store
var files = {};
// html element of file list
var $files = null;
//add file to file list
function addFile(file) {
//add files with diferent name, max files count 5
if (!(file.name in files) && Object.keys(files).length < 5) {
var div = createFile(file.name);
$files.appendChild(div);
files[file.name] = {
file: file,
element: div
}
}
}
//create html element with file name
function createFile(name) {
var div = document.createElement("div");
div.innerText = name;
var input = document.createElement("input")
//remove on click
div.addEventListener("click", function () {
$files.removeChild(this);
delete files[name];
})
return div;
}
window.addEventListener("load", init);
<form method="post" enctype="multipart/form-data" action="">
<label>Name<input name="name" /></label>
<label>Last name<input name="lastName" /></label>
<label>Email<input name="email" /></label>
<div id="dragdrop" style="width: 300px; height: 300px; background-color:lightgray">Drag drop zone</div>
<div id="files"></div>
<button type="submit">Send</button>
</form>

How to get the fileName in javascript from input file tag in IE browser

I have done this in jQuery, to get filename from input file tag, With jQuery it works perfectly.
//jQuery('input[type=file]').on('change', prepareUpload);
document.getElementsByTagName('input[type=file]').addEventListener('change',prepareUpload1,true);
/*
//this works in jQuery
function prepareUpload(event)
{
var files = event.target.files;
var fileName = files [0].name
alert(fileName);
}
*/
/****Check it here ****/
// it does not work in javascript
function prepareUpload1(event)
{
var files = event.target.files;
var fileName = files [0].name
alert("fileName 2 : "+fileName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />
But I found Event.target does not work in IE, I tried to change it to java script addeventlistener, it did not work.
It throws error
Uncaught ReferenceError: input is not defined
It is working in jQuery but it is not working in JS, Due to IE issue I need to change it to JS.
Can some one help
I found the problem to be in getElementsByTagName method, you use this when you have a group of elements with the same tag name.
Try this code below, it works
//HTML
<input id="inp" type="file" />
// JavaScript
document.getElementById('inp').addEventListener('change',prepareUpload,false);
function prepareUpload(event)
{
var files = event.target.files;
var fileName = files[0].name;
alert(fileName);
}
Below is the code if you want to do it for more than one element
<body>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<script>
var inputArray = document.getElementsByClassName('input');
for(var i = 0; i < inputArray.length; i++){
inputArray[i].addEventListener('change',prepareUpload,false);
};
function prepareUpload(event)
{
var files = event.target.files;
var fileName = files[0].name;
alert(fileName);
}
</script>
</body>
This will work
var fileName = $("input[type='file']").val().split('/').pop().split('\\').pop();
The code above is correct for all but IE simply because IE doesn't like event.target - you need event.srcElement: https://developer.mozilla.org/en-US/docs/Web/API/Event/srcElement
So something like this should sort that out:
var files;
if (window.navigator.userAgent.indexOf("MSIE ") > 0) ?
files = event.srcElement.files :
files = event.target.files;
I couldn't make that work in the "Run Snippet" thing SO has, though, so here's how you can just get it using another button:
document.getElementById('myBtn').addEventListener('click', function() {
doUpload();
});
function doUpload()
{
var myFile = myInput.files[0];
// can also use var myFile = document.querySelector('input').files[0];
var fileName = myFile.name;
alert(fileName);
}
<input id="myInput" type="file" />
<button id="myBtn">Try Me</button>

Categories