Empty excel file is uploaded in JavaScript - javascript

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?

Related

How to use simplexlsxgen in php to Generate sheet and download in ajax javascript while sharing JS array from jacascript to php using ajax

I have been trying to generate an excel sheet and download using simplexlsxgen (PHP)
Here is my Github documentation too
Link
What I Need
I have a JSON Array in my javascript I have to pass it to the PHP file through javascript AJAX where I generate my excel sheet and download it to my Local disk
The Sample Code I have Tried
In my index.php file
<html>
<body>
Export to Excel Sheet
</body>
</html>
In My export.php file
<?php
include ("SimpleXLSXGen.php");
$books = [
['Monday', 'App', 'Lynley Dodd', 'Mallinson Rendel', 'NZ'],
['', 'Pos', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
];
$xlsx = Shuchkin\SimpleXLSXGen::fromArray( $books );
$xlsx->mergeCells('A3:A5');
$xlsx->mergeCells('A6:A8');
$xlsx->mergeCells('A9:A11');
$xlsx->mergeCells('A12:A14');
$xlsx->mergeCells('A15:A17');
$xlsx->mergeCells('A18:A20');
$xlsx->mergeCells('A21:A23');
$xlsx->mergeCells('A24:A26');
$xlsx->mergeCells('C1:L1');
$xlsx->saveAs('books.xlsx');
$xlsx->downloadAs('books.xlsx');
?>
Conclusion
If I Use the above code the array is converted to an excel sheet and downloaded successfully.
The Problem
!. I have the array in my javascript file So I have to pass that array From my Javascript to my PHP File using ajax javascript.
$.ajax({
url: 'export.php',
data: {
books:books
},
type: 'POST',
success: function(response) {
}
});
But If I just pass the data like this the excel sheet is not downloading.
The alternative Code I have tried
In my index.php file
<html lang="en">
<head>
<title>JS array to Excel</title>
</head>
<script>
function array2excel() {
var books = [
["ISBN", "title", "author", "publisher", "ctry"],
[618260307, "The Hobbit", "J. R. R. Tolkien", "Houghton Mifflin", "USA"],
[908606664, "Slinky Malinki", "Lynley Dodd", "Mallinson Rendel", "NZ"]
];
var json = JSON.stringify(books);
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
var file = new Blob([this.response], {type: this.getResponseHeader('Content-Type')});
var fileURL = URL.createObjectURL(file);
var filename = "", m;
var disposition = this.getResponseHeader('Content-Disposition');
if (disposition && (m = /"([^"]+)"/.exec(disposition)) !== null) {
filename = m[1];
}
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = fileURL;
} else {
a.href = fileURL;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
alert("Error: " + this.status + " " + this.statusText);
}
}
request.open('POST', "array2excel.php");
request.responseType = "blob";
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("array2excel=" + encodeURIComponent(json));
}
</script>
<body>
<input type="button" onclick="array2excel()" value="array2excel" />
</body>
</html>
In my array2excel.php file
<?php // array2excel.php
if (isset($_POST['array2excel'])) {
require __DIR__.'/simplexlsxgen/src/SimpleXLSXGen.php';
$data = json_decode($_POST['array2excel'], false);
\Shuchkin\SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
return;
}
?>
Problem with the Alternative code
The file is downloading but the file is been corrupted and downloaded as an HTML file instead of an excel Sheet File.
What Do I Need
I need to pass My JSON array which is in my javascript to the export/array2excel.php file using javascript ajax using the post method
welcome to suggest any alternative.

Javascript: Upload a file from inside a tar file

I have an HTML form that is used to upload a file to the server. This works correctly but now I am trying to expand the capability such that I select a tar file that consists of two binary files. Then untar the files and based on certain conditions either upload the first or the second file.
This is what I have done so far
use FileReader to read the tar file as ByteArray
use untar from js-untar to untar both file
I need help to figure out how to take the ByteArray for either files and add then to the FormData so that I can upload them.
Any help would be appreciated.
Here are snippets from my code
HTML Form
<form id="upform" enctype="multipart/form-data"
action="cgi-bin/upload2.cgi">
Firmware file: <input id='userfile' name="userfile" type="file" width=50 >
<input type
="submit" name="submitBtn" value="send file">
</form>
Untar code
function sendData() {
var formData = new FormData(form);
var action = form.getAttribute('action');
filesize = file.files[0].size;
var reader = new FileReader();
reader.onload = function() {
untar(reader.result).then(
function (extractedFiles) { // onSuccess
console.log('success');
formData.delete('userfile');
var reader2 = new FileReader();
reader2.onload = function() {
formData.append('userfile', reader2.result);
upload(formData);
}
var blob = new Blob([extractedFiles[0]], {type : 'multipart/form-data'});
reader2.readAsDataURL(blob);
// var f = URL.createObjectURL(blob);
},
function (err) {
console.log('Untar Error');
}
)
};
reader.readAsArrayBuffer(file.files[0]);
return;
}
function upload(formData) {
var action = form.getAttribute('action');
reqUpload.open('POST', action, true);
reqUpload.onreadystatechange = uploadState;
document.body.style.cursor = "wait";
var ld = document.getElementById("load");
ld.classList.add("loader");
reqUpload.send(formData);
document.getElementById('progress').style.display = "block";
progTimer = setInterval(ping, 10000);
uploadStarted = true;
return;
}

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.

HTML5 File Handeling in JavaScript?

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>

Categories