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

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

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>

collect multiple inputs file to append to FormData

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>

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 attach a file with FormData and Blob?

I am trying to attach a file and upload through ajax request. But it creates a new file instead of uploading the file I am trying to provide.
var formData = new FormData();
var blob = new Blob([JSON.stringify({})], {type : 'application/json'});
formData.append("file", blob, "sample.txt");
When I open the file I can see the content getting replaced with {}
Code mentioned will only create and empty form object. If you need to upload that form object to server, use following similar code.
var formElement = document.querySelector("form");
var formData = new FormData(formElement); //reads user input data from form
/**var blob = new Blob([JSON.stringify({})], {type : 'application/json'}); //added {} to form
formData.append("file", blob, "sample.txt"); //names file and keeps {} as content ----not needed**/
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php"); //put ypur end point here
request.send(formData); //send to server
your form html should look something like this
<form enctype="multipart/form-data" method="post" name="submitform">
<label>File to upload:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
Please read more on this here

how to send json data and 1-n files in POST body use javascript

I have from like this:
<form id="form" method='post' action="http://192.168.1.33/api/" enctype="multipart/form-data">
<label>User login: </label>
<input type="text" id="userLogin"><br />
<label>User password</label>
<input type="text" id="userPass"><br /><br />
<label>Input command here</label>
<input type="text" size="100" placeholder="users" id="command" name="command"><br/><br />
<input type="file" name="file1"><br/>
<input type="file" name="file2"><br/>
<br />
<input type="submit">
</form>
<h3>Output: </h3>
<div id="output"></div>
And simple javascript code. This code gets form data (attached files) and creating 2 fields in http header with userName and userPass, and send it to my api:
<script type="application/javascript">
var myCommand = document.querySelector('#command');
document.forms[0].onsubmit = function (event) {
if (window.FormData) {
event.preventDefault();
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var url = form.getAttribute('action') + '?' + myCommand.value;
xhr.open('post', url);
xhr.setRequestHeader('x-auth-user', document.querySelector('#userLogin').value);
xhr.setRequestHeader('x-auth-pass', document.querySelector('#userPass').value);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// server response: xhr.responseText
document.querySelector('#output').innerHTML = this.responseText;
}
};
xhr.send(data);
}
};
(function() {
document.querySelector('#userLogin').value = "user1";
document.querySelector('#userPass').value = "user";
})();
</script>
How can I add json data in body request use javascript? Json like this:
{
"id":"",
"status":0,
"documentName":"user",
"documentDesctiption":"",
"documentAttachedUsers":"id, id, id"
}
In fact I don't need form. I need to send 1-n files and one json string in POST body.
Now Api (php) receives just only form data (files). I plan on getting the body like this:
$inputJSON = file_get_contents('php://input');

Categories