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.
Related
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>
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 :-)
I'm trying to upload and download the excel file in a single click operation. I'm calling two APIs in a single operation. The download operation is working fine. But during file upload, an empty excel file is being uploaded with the exact file-name. This is the server side code
Excel Duplicates Remover in JAVA. The server-end works fine. And this is the client-side code.
<!DOCTYPE html>
<html>
<body>
Select a file: <input type="file" id="file" accept=".csv, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" multiple size="50"/><br>
Keyword:<input type="text" id="columnHeading"/><br>
<button type="button" onclick="downloadDoc()">Request data</button>
<script>
function downloadDoc(){
var fileTab = document.getElementById("file");
var columnHeading = document.getElementById("columnHeading");
if('files' in fileTab) {
if(fileTab.files.length == 1) {
var url = 'http://localhost:8080/excel-duplicate-remover/rest/fileService/';
var uploadUrl = url + "upload";
var file=fileTab.files[0];
var formData = new FormData();
formData.append("columnHeading",columnHeading);
formData.append("file",file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var path = response.path;
var downloadUrl = url + 'downloadFile?fileName=' + path;
downloadFile(downloadUrl);
}
};
xhr.open("POST", uploadUrl);
xhr.send(formData);
}else{
console.log("file not present");
}
}
}
function downloadFile(filename) {
console.log("filename"+filename);
var link = document.createElement('a');
// Add the element to the DOM
link.setAttribute("type", "hidden"); // make it hidden if needed
link.href = filename;
link.download;
document.body.appendChild(link);
link.click();
link.remove();
}
</script>
</body>
</html>
Why is the file being uploaded as an empty excel file?
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>
What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>