Javascript: How to upload file onsubmit()? - javascript

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>

Related

Sending cropped image blob with xmlhttprequest to flask server

Form
<h2 class="uk-modal-title">Change Profile Picture</h2><br>
<form action="{{url_for('upload_dp', username=username)}}" method="POST" enctype="multipart/form-data">
<input type="file" accept="image/*" placeholder="Upload profile picture" onchange="loadFile(event)" id="uploaded" required>
<img id="dp">
<button onclick="beforeSubmit()">Upload</button>
Javascript
var cropper;
function loadFile(image) {
var dp = document.getElementById('dp');
dp.src = URL.createObjectURL(image.target.files[0]);
dp.onload = function() { URL.revokeObjectURL(dp.src)};
cropper = new Cropper(dp, { aspectRatio: 1 });
}
function beforeSubmit() {
cropper.getCroppedCanvas().toBlob((blob) => {
var formData = new FormData();
formData.append("dp", blob);
formData.append('username', '{{username|safe}}');
var xhr = new XMLHttpRequest;
xhr.open( "POST", "/upload_dp");
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);
}, "image/jpeg");
}
When an image is uploaded for , it renders and a cropper appears on it. Till here, things work fine.
User, changes cropper according to his need and on pressing button Upload, function beforeSubmit runs where the problem lies. I do not receive any files in the flask application. The request below has non-empty stream and I receive the argument username, but the file dp having cropped image as blob is not received! Please help.
print(request.__dict__)
Is stream the blob file? How are xmlhttprequest with files seen in flask?

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

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