Using javascript to save base64 String to excel (.xls) file? - javascript

I converted a excel file as base64 String as web backend side, and could recover it as excel file as expected with Java code below:
String destinationPath = "e:\out1.xls";
//decode Base64 String to excel file
FileOutputStream fos = new FileOutputStream(destinationPath);
bytes = new sun.misc.BASE64Decoder().decodeBuffer(content);
fos.write(bytes);
fos.flush();
fos.close();
I can response frontend with base64 string, but I always got messy code when I tried to export it as excel (.xls) file using javascript. Below is the code:
onClick: function(){
// below is base64 String snippet.
var base64Str = "0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAOwADAP7/CQAGAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA\r\nEAAA/v///wAAAAD+////AAAAAAEAAAD/////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n//////////////////////////////////////////////////////////////////////////9S\r\nAG8AbwB0ACAARQBuAHQAcgB5AAAAAAAAAAAAAA .........";
base64Str = base64Str.replace(/\\r\\n/g,"");
var decoder = Ext.util.Base64.decode(fileStr);
testApp.view.main.FileExport.saveAs(decoder,'SHANGTOUDI_JF_20180320_0800.xls','UTF-8');
}
Need to say, I can use this method to export txt file successfully. Any suggestion are appreciated.

Related

Javascript: how to parse base64 encoded csv to fetch the filename and actual csv content

I have a base64 string created by encoding a csv file,
const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzdiINCkNvbnRlbnQtVHlwZTogdGV4dC9jc3YNCg0K77u/QWNjb3VudE51bWJlcixBY2NvdW50TmFtZSxEZWR1Y3RhYmlsaXR5DQoxMTExLHRlZWUsMTAwDQoyMjIyMix0ZXN0LDEwMA0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNC0tDQo='
I want to get the name of the file and create the same file back with the filename. What I need to use. I am using node.js here.
If I understand your question right, your base64 variable needs to be decoded. buffer can do this:
const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzdiINCkNvbnRlbnQtVHlwZTogdGV4dC9jc3YNCg0K77u/QWNjb3VudE51bWJlcixBY2NvdW50TmFtZSxEZWR1Y3RhYmlsaXR5DQoxMTExLHRlZWUsMTAwDQoyMjIyMix0ZXN0LDEwMA0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNC0tDQo=';
// decode base64
const decodedBase64String = Buffer.from(base64, 'base64').toString();
const filename = decodedBase64String.match(/filename="(.*).csv/)[1];
console.log(decodedBase64String);
With a some regex you can extract your filename ("chartOfAccount.csv") from decodedBase64String. And then use fs (explained here) to create from your content a file.

How to decode utf-8 files from btoa(unescape(encodeURIComponent(file))) in Python?

I want to upload any file (Word, PDF, Image ...) with an HTML file input to a python server.
With the help of snakecharmerb (Upload file as JSON to Python webserver) I can send the file by encoding it in the following way in JavaScript:
function fileChange(event) {
const file = event.target.files[0];
const fileReader = new FileReader();
fileReader.onload = function(e) {
const encodedFile = btoa(unescape(encodeURIComponent(e.target.result)));
uploadFile(JSON.stringify(encodedFile), file.name);
}
fileReader.readAsText(file);
}
In Python, I can read and save the file in the following way:
import json
from base64 import b64decode
binary_data = b64decode(json.loads(file));
with open(file_name, "wb") as f:
f.write(binary_data)
But the resulting file is not readable or the content is not correct encoded. I think i need to encode the binary_data in utf-8. But binary_data.encode("utf-8") results in an error.
test_file.txt
Hello World!
Special chars: äöüß
Python error
UnicodeDecodeError('ascii', 'Hello World!\r\nSpecial chars: \xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd', 29, 30, 'ordinal not in range(128)')
I also tried combining it with .decode('string_escape')

Upload file as JSON to Python webserver

I want to upload a file as JSON from the client to a Python webserver (Tornado) and save it on the server. This is my simplified setup:
Client HTML:
<input type="file" id="myFile" onchange="fileChange" />
Client JS:
function fileChange(event) {
const file = event.target.files[0];
const fileReader = new FileReader();
fileReader.onload = (e) => uploadFile(e.target.result, file.name);
fileReader.readAsText(file);
}
function uploadFile(fileContent, fileName) {
const data = {fileContent, fileName};
axios.post('http://localhost:8080/api/uploadFile', JSON.srtingify(data));
}
Python Webserver:
class UploadFileHandler(tornado.web.RequestHandler):
def post(self):
requestBody = tornado.escape.json_decode(self.request.body)
file = open(requestBody["fileName"], "w+")
file.write(requestBody["fileContent"].encode("UTF-8"))
file.close()
All uploaded files are empty (blank pages in a PDF, file type of JPG is 'not supported', Word file cannot be opened) and are nearly twice as big as the original file. How can I fix this?
Is there a way to improve this setup?
You are trying to upload binary files (word, jpg), serialised as JSON, and store them on the server.
To handle binary data in JSON, encode the binary data as base64 first, then call JSON.stringify.
Like this (untested):
function uploadFile(fileContent, fileName) {
// Encode the binary data to as base64.
const data = {
fileContent: btoa(fileContent),
fileName: fileName
};
axios.post('http://localhost:8080/api/uploadFile', JSON.stringify(data));
}
On the server side, you need to deserialise from JSON, decode the base64 and the open a file in binary mode to ensure that what you are writing to disk is the uploaded binary data. Opening the file in text mode requires that the data be encoded before writing to disk, and this encoding step will corrupt binary data.
Something like this ought to work:
class UploadFileHandler(tornado.web.RequestHandler):
def post(self):
requestBody = tornado.escape.json_decode(self.request.body)
# Decode binary content from base64
binary_data = base64.b64decode(requestBody[fileContent])
# Open file in binary mode
with open(requestBody["fileName"], "wb") as f:
f.write(binary_data)

Convert Base64String back to xls at frontend

Backend converts the xls file into base64 String and returns in the http response.On the browser, any way to convert it back to xls for downloading?
It is not necessary to convert the base64 string any further. Add the necessary portions to base64 string to form a valid data URI, then proceed to offer file for download.
const mime = "data:application/vnd.ms-excel,";
const data = mime + base64string;

How to convert a PDF file into a base64 string in java script

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs.
I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript.
Can anybody tell me how to do it?
See if your JavaScript environment has the "atob" and "btoa" functions available:
var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string
These convert a string to and from Base64 encoding.
Trying using the logic below.
<input id="inputFile" type="file" onchange="convertToBase64();" />
function convertToBase64(){
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
Note : This snippet was taken from stackoverflow, but I dont remember the link :(

Categories