collect multiple inputs file to append to FormData - javascript

Suppose I have the following form.
<form id="testForm">
<input type="file" name="uploads[]"><br/>
<input type="file" name="uploads[]"><br/>
<input type="file" name="uploads[]"><br/>
<input type="submit">
</form>
And this is part of the submit code which tries to collect files to append to FormData, but I don't know how to do it properly.
var formData = new FormData();
var fileList = $("input[name='uploads[]']");
for(var x = 0; x < fileList.length; x++) {
formData.append('file'+x, ???);
console.log('appended a file');
}
var request = new XMLHttpRequest();
request.open('POST', '/upload');
request.send(formData);
request.onload = function(e) {
console.log('Request Status', request.status);
};
This is the server code.
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
console.log('handling form upload - fields', fields);
console.log('handling form upload - files', files);
});
res.send('Thank you');
});
If it works, I expect to see output and files saved in /tmp.

You don't have to collect fields since you can put the form itself into FormData object:
var form = document.getElementById('testForm');
form.addEventListener('submit', function(e) {
e.preventDefault();
var request = new XMLHttpRequest();
request.open('POST', '/upload');
request.onload = function(e) {
console.log('Request Status', request.status);
};
var formData = new FormData(form);
request.send(formData);
});
UPDATE
If you need to upload several files, you might use multiple attribute on the input instead of several inputs:
<form id="testForm">
<input type="file" name="upload" multiple>
<input type="submit">
</form>

Related

Javascript: How to upload file onsubmit()?

I have a JSP page with <form> that uploads a file on submit.
But the upload function is not uploading any file to the server at the path /uploads.
HTML form:
<form action="./index.jsp" onsubmit="uploadFile()">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>
Javascript function to upload file:
<script>
function uploadFile(){
let excel = document.getElementById("excelInput").files[0]; // file from input
alert(excel);
let req = new XMLHttpRequest();
let formData = new FormData();
try{
formData.append("excel", excel);
req.open("POST", 'D:\\eclipse\\workspace\\Project2\\WebContent\\uploads');
req.send(formData);
}
catch(e){
alert(e);
}
}
</script>
It is not going to the catch() section. But it isn't uploading either.
Is there anything missing ?
The dupes seems to be very poor, so I post an answer.
You basically want to add an eventListener AND submit to a WEB SERVICE! Not a file location
window.addEventListener("load", function() {
document.getElementById("uploadForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop the submit
let excel = document.getElementById("excelInput").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
try {
formData.append("excel", excel);
req.open("POST", 'actual web address of a process that can handle xmlhttprequests');
req.send(formData);
} catch (e) {
console.log(e);
}
})
})
<form action="./index.jsp" id="uploadForm">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>

esp8226 with javascript

I am trying to make a UI for esp8226 html js, ajax everything works fine but when I try to upload the firmware(uxx.bin) file it doesn't work.
Reference : https://github.com/jeelabs/esp-link/blob/master/html/flash.js
Note : I am connected to same network using wifi and the html page loads quite good.
I am trying to upload two files 1 --> uxx.bin
once it uploads redirect to next page and upload 2 --> uyy.bin
Here is the code
Html
<form id="file-form" action="uxx.bin" method="POST">
<input type="file" id="file-select" name="user[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('user[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uxx.bin', true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
if anyone can guide with the correct approach :-)

How to upload a file using javascript?

I want to create an uploader with js. Can anyone help me how to upload a file using javascript?
You can use html5 file type like this:
<input type="file" id="myFile">
You file will be in value:
var myUploadedFile = document.getElementById("myFile").files[0];
For more information see https://www.w3schools.com/jsref/dom_obj_fileupload.asp
and see example here: https://www.script-tutorials.com/pure-html5-file-upload/
You can upload files with XMLHttpRequest and FormData. The example below shows how to upload a newly selected file(s).
<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {
const fd = new FormData();
// add all selected files
e.target.files.forEach((file) => {
fd.append(e.target.name, file, file.name);
});
// create the request
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// we done!
}
};
// path to server would be where you'd normally post the form to
xhr.open('POST', '/path/to/server', true);
xhr.send(fd);
});
</script>
HTML Part:
<form enctype = "multipart/form-data" onsubmit="return false;" >
<input id="file" type="file" name="static_file" />
<button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
</form>
JavaScript Part:
function uploadFile(form){
const formData = new FormData(form);
var oOutput = document.getElementById("static_file_response")
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload_static_file", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
console.log(oReq.response)
} else {
oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
}
};
oOutput.innerHTML = "Sending file!";
console.log("Sending file!")
oReq.send(formData);
}
In the above HTML, I'm using the form to capture the files and calling the JS function when the button is clicked. In the JS function, I'm using the XMLHttpRequest to send the file.
A detailed step-by-step document can be found here.

How to manipulate FileList type=file and sending via Ajax?

I need some help for my problem. I want to delete some files from a FileList and then send them via Ajax with new FormData. For this I only want to work with Javascript.
After the files have been selected by users, they are evaluated by the content_evaluate () function and the files to be sent are assigned to a new array transfer_files[]. These files are added to a new formdata and then sent.
However, all files from the origin input are sent even if only the modified array is given to the new formdata. e.g. 3 of 5 files have to be sent.
<form id="formular" onsubmit="send_data();" method="post"
enctype="multipart/form-data">
<table id="dyninfo" align="center" border="1">
<tr>
<td>
<input id="upload_filename_id" name="upload_filename" type="file"
onchange="content_evaluate();" size="60" multiple>
</td>
<td>
<button type="submit" id="upload" style="width:120px">Upload</button>
</td>
</tr>
</table>
</form>
Script:
var transfer_files = [];
function send_data()
{
var formData = new FormData();
for (var i = 0; i < transfer_files.length; i++)
{
var file = transfer_files[i];
formData.set(transfer_files, file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.html', true);
xhr.send(formData);
return false;
};
You were looping through a 0 length array ( transfer_files )
What you should have done instead:
Use the input file object to retrieve the inputted files, then you can loop through it
var inputFile = document.querySelector('#upload_filename_id'),
transfer_files = inputFile.files;
function send_data()
{
var i, file, formData = new FormData();
for ( i = 0; i < transfer_files.length; i++ )
{
file = transfer_files[ i ];
formData.set( inputFile.name, file, file.name );
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.html', true);
xhr.send(formData);
return false;
};

AJAX - How to get data from input file to append formdata?

Hello I want to use pure javascript ajax (no jquery) to append formdata but I don't know how to get data from input file type
function handleForm(e)
{
e.preventDefault();
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username);
data.append('email', email);
data.append('file', ?????); ////// How to get data from input file
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test2.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
...
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Image: <input type="file" name="file" id="myimg"><br/>
<input type="submit">
</form>
The <input type="file" /> HTML element has a files property (of type FileList).
Check the length if a file has been selected and if so add the file(s) to the FormData object
var fileInput = document.getElementById("myimg");
if (fileInput.files.length > 0) {
data.append("file", fileInput.files[0]);
}
For more examples on how to use the FormData object check this link:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
document.getElementById("file_input_id").files[0]
try
<input type="file" id="fileinput" />
to get file.. you can use
var myFile = $('#fileinput').prop('files')[0];

Categories