Excel file from server to client | Javascript - javascript

What I want to do: I have on the server side a file 'test_download.xlsx', and want to send it to the client side so that I can apply XLSX.read() on the retrieved object.
So I tried it this way
Server :
let filename = 'test_download.xlsx';
const buffer = fs.readFileSync(filename)
res.json(buffer);
Client :
file = await axios.get('/dataexplorer/test');
console.log(file);
console.log(XLSX.read(file.data, {type: "buffer"}));
First log :
Second log :
The problem is that it doesn't match my excel file at all just in terms of sheets (my file has 3 different sheet names)
Do you have any idea what the problem is?
Thanks

On the server-side just use:
const filename = 'test_download.xlsx';
// make sure to include the name and the extension of the file in the path
const filepath = 'your/path/to/the/file/test_download.xlsx';
/** filename is optional:
* if you don't pass it, the name of the file in the filepath will be used
* if you pass it the file at hte filepath will be downloaded with the name of `filename`
*/
res.download(filepath, filename);
This will return a blob to the client(make sure to include the correct headers for the response type) and then you can just save it or work with it with :
file = await axios.get('/dataexplorer/test',{ responseType: "blob"});
const ab = await file.data.arrayBuffer();
XLSX.read(Buffer.from(ab),{type:"buffer"})

Related

Attempting to download a .xlsx file and upload to Azure Blob Storage using Playwright with Javascript produces malformed .xlsx file with a bad header

I am trying to download an excel file and then upload it to Azure Blob Storage for use in Azure Data Factory. I have a playwright javascript that worked when the file was a .csv but when I try the same code with an excel file, it will not open in Excel. It says,
"We found a problem with some content in 'order_copy.xlsx'. Do you want us to try to recover as much as we can?:
After clicking yes, it says,
"Excel cannot open the file 'order_copy.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
Any ideas on how to use the createReadStream more effectively to do this and preserve the .xlsx format?
I don't think the saveAs method will work since this code is being executed in an Azure Function with no access to a local known path.
My first thought was the content type was not right, so I set that, but it still did not work. I tried a UTF-8 encoder but that also did not work.
//const data = await streamToText(download_csv.createReadStream())
const download_reader = await download_csv.createReadStream();
let data = '';
for await (const chunk of download_reader) {
data += chunk; //---I suspect I need to do something different here
}
// const data_utf8 = utf8.encode(data) //unescape( encodeURIComponent(data) );
const AZURE_STORAGE_CONNECTION_STRING = "..." //---Removed string here
// Create the BlobServiceClient object which will be used to create a container client
const blob_service_client = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
// Get a reference to a container
const container_client = blob_service_client.getContainerClient('order');
const blob_name = 'order_copy.xlsx';
// Get a block blob client
const block_blob_client = container_client.getBlockBlobClient(blob_name);
const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const blobOptions = { blobHTTPHeaders: { blobContentType: contentType } };
//const uploadBlobResponse = await block_blob_client.upload(data_utf8, data_utf8.length, blobOptions);
const uploadBlobResponse = await block_blob_client.upload(data, data.length, blobOptions);
console.log("Blob was uploaded successfully. requestId: ", uploadBlobResponse.requestId);
Any guidance would be appreciated. Thank you in advance for your help!
-Chad
Thanks #Gaurav for the suggestion on not setting the data to a string. The following code worked after I changed to using a array of the chunks and concatenated it using the Buffer similar to your suggested code.
let chunks = []
for await (const chunk of download_reader) {
chunks.push(chunk)
}
const fileBuffer = Buffer.concat(chunks)
...
const uploadBlobResponse = await block_blob_client.upload(fileBuffer, fileBuffer.length, blobOptions);
Thanks everyone!

Angular8 - Downloading Excel .xlsx saves base64 string in file

I've studied all of the SO Similar Questions about this problem, a few were helpful, but did not directly address the saving of an xlsx file to the local Win10 downloads folder.
The xlsx file sits on a CentOS 7 server. If I use Filezilla to copy it to Win10, it's fine.
Looking at the component code below, I am reading the xlsx from the server and getting its base64Str, which matches exactly what I used to store the file. I create a blob fine, but FileSaver, saves the Win10 file with its contents as the base64Str, instead of a an xlsx binary. Can FileSaver save binary content, or only text?
Thanks for helping!
Component Code
//INPUT DATA: docName: test.xlsx; mediaType: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; snippet base64Str: VUVzREJCUU...FBQUFBPQ=
//NOTE: input data is from a CentOS 7 filesystem
const byteStr = atob(base64Str);
const arrayBuffer = new ArrayBuffer(byteStr.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteStr.length; i++) {
int8Array[i] = byteStr.charCodeAt(i);
}
const blob = new Blob([arrayBuffer], { type: mediaType }); //also tried type: 'application/octet-stream'
//alternate technique that produces same corrupted result
//const base64Response = await fetch(`data:` +mediaType +`;base64,${base64Str}`);
//const blob = await base64Response.blob();
fileSaver.saveAs(blob, docName); //saves to Win10 downloads folder
Please try The below code. (Here in this example I have demonstrate the following 1) Input base64 string to a input text area 2) on click of download file link 3) will prompt to download the file into correct xlsx format without corrupted data).
Kindly modify the code as per your need . Example only demonstrate the file download feature.
Point to notice :
var mediaType="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
function saveAsXlsxFile(){
var mediaType="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
var userInp = document.getElementById('base64input');
// var userInp = "UEsDBBQABgAIAAAAIQBBN4LPbgEAAAQFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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hcmVkU3RyaW5ncy54bWxQSwECLQAUAAYACAAAACEAO20yS8EAAABCAQAAIwAAAAAAAAAAAAAAAAD0GgAAeGwvd29ya3NoZWV0cy9fcmVscy9zaGVldDEueG1sLnJlbHNQSwECLQAUAAYACAAAACEAo9Y9cDYBAADkAgAAJwAAAAAAAAAAAAAAAAD2GwAAeGwvcHJpbnRlclNldHRpbmdzL3ByaW50ZXJTZXR0aW5nczEuYmluUEsBAi0AFAAGAAgAAAAhAFSTEGpDAQAAawIAABEAAAAAAAAAAAAAAAAAcR0AAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAGAAgAAAAhAGFJCRCJAQAAEQMAABAAAAAAAAAAAAAAAAAA6x8AAGRvY1Byb3BzL2FwcC54bWxQSwUGAAAAAAwADAAmAwAAqiIAAAAA";
var a = document.createElement('a');
a.href = mediaType+userInp.value;
//a.href = mediaType+userInp;
a.download = 'filename.xlsx';
a.textContent = 'Download file!';
document.body.appendChild(a);
}
<textarea placeholder="paste the base64 data here, exclude readable headers" id='base64input' type="textarea"></textarea>
<br>
<input onclick="saveAsXlsxFile()" type="button" value="update content of link"></button>
HTML code for demo only ( not mandatory for your requirement)
<textarea placeholder="paste the base64 data here, exclude readable headers" id='base64input'></textarea>
<br>
<input onclick="saveAsXlsxFile()" type="button" value="update content of link"></button>
Sample userInp value Try this :
UEsDBBQABgAIAAAAIQBBN4LPbgEAAAQFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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C5yZWxzUEsBAi0AFAAGAAgAAAAhAAdhSeKLAgAARAYAABgAAAAAAAAAAAAAAAAAiQwAAHhsL3dvcmtzaGVldHMvc2hlZXQxLnhtbFBLAQItABQABgAIAAAAIQDBFxC+TgcAAMYgAAATAAAAAAAAAAAAAAAAAEoPAAB4bC90aGVtZS90aGVtZTEueG1sUEsBAi0AFAAGAAgAAAAhACBSf139AgAAwgcAAA0AAAAAAAAAAAAAAAAAyRYAAHhsL3N0eWxlcy54bWxQSwECLQAUAAYACAAAACEAw//qhdEAAACPAQAAFAAAAAAAAAAAAAAAAADxGQAAeGwvc2hhcmVkU3RyaW5ncy54bWxQSwECLQAUAAYACAAAACEAO20yS8EAAABCAQAAIwAAAAAAAAAAAAAAAAD0GgAAeGwvd29ya3NoZWV0cy9fcmVscy9zaGVldDEueG1sLnJlbHNQSwECLQAUAAYACAAAACEAo9Y9cDYBAADkAgAAJwAAAAAAAAAAAAAAAAD2GwAAeGwvcHJpbnRlclNldHRpbmdzL3ByaW50ZXJTZXR0aW5nczEuYmluUEsBAi0AFAAGAAgAAAAhAFSTEGpDAQAAawIAABEAAAAAAAAAAAAAAAAAcR0AAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAGAAgAAAAhAGFJCRCJAQAAEQMAABAAAAAAAAAAAAAAAAAA6x8AAGRvY1Byb3BzL2FwcC54bWxQSwUGAAAAAAwADAAmAwAAqiIAAAAA
Happy to help further if needed. :)
so I used this. Might also work for anyone trying to convert a static base 64 string to xlxs file. This solutions assumes that you know the file type.
let toConvert = 'UEsDBBQAAAgIABSJA..'//supply your full plain string here
let file = `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${toConvert}`;
setTimeout(() => {
fileSaver.saveAs(file, 'fileName');
}, 1300);//timeout is only added to simulate time to load. you can take it out
Regards
Not sure if this works , but try setting the mediaType like below :
const mediaType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';

How do you upload a blob base64 string to google cloud storage using Node.js

I'm building an application that will allow me to take a picture from my react app which accesses the web cam, then I need to upload the image to google cloud storage using a Hapi node.js server. The problem I'm encountering is that the react app snaps a picture and gives me this blob string (I actually don't even know if that's what it's called) But the string is very large and looks like this (I've shortened it due to it's really large size:
"imageBlob": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
I'm finding it hard to find resources that show me how to do this exactly, I need to upload that blob file and save it to a google cloud storage bucket.
I have this in my app so-far:
Item.postImageToStorage = async (request, h) => {
const image = request.payload.imageBlob;
const projectId = 'my-project-id'
const keyFilename = 'path-to-my-file'
const gc = new Storage({
projectId: projectId,
keyFilename: keyFilename
})
const bucket = gc.bucket('my-bucket.appspot.com/securityCam');
const blob = bucket.file(image);
const blobStream = blob.createWriteStream();
blobStream.on('error', err => {
h.response({
success: false,
error: err.message || '=-->' + err
})
});
console.log('===---> ', 'no errors::::')
blobStream.on('finish', () => {
console.log('done::::::', `https://storage.googleapis.com/${bucket.name}/${blob.name}`)
// The public URL can be used to directly access the file via HTTP.
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
);
});
console.log('===---> ', 'past finish::::')
blobStream.end(image);
console.log('===---> ', 'at end::::')
return h.response({
success: true,
})
// Utils.postRequestor(path, payload, headers, timeout)
}
I ge to the success message/response h.response but no console logs appear except the ones outside of the blobStream.on I see all that start with ===---> but nothing else.
Not sure what I'm doing wrong, thanks in advance!
At the highest level, let us assume you want to write into file my-file.dat that is to live in bucket my-bucket/my-folder. Let us assume that the data you want to write is a binary chunk of data that is stored in a JavaScript Buffer object referenced by a variable called my_data. We would then want to code something similar to :
const bucket = gc.bucket('my-bucket/my-folder');
const my_file = bucket.file('my-file.dat');
const my_stream = my_file.createWriteStream();
my_stream.write(my_data);
my_stream.end();
In your example, something looks fishy with the value you are passing in as the file name in the line:
const blob = bucket.file(image);
I'm almost imagining you are thinking you are passing in the content of the file rather than the name of the file.
Also realize that your JavaScript object field called "imageBlob" will be a String. It may be that it indeed what you want to save but I can also imagine that what you want to save is binary data corresponding to your webcam image. In which case you will have to decode the string to a binary Buffer. This looks like it will be extracting the string data starting data:image/jpeg;base64, and then creating a Buffer from that by treating the string as Base64 encoded binary.
Edit: fixed typo

Generate pdf files with Weasyprint, save in zip file, send that zip file to client and present it for download

Let me break down my requirement. Here's what I'm doing right now.
1. Generate PDF files from HTML
for this I'm using Weasyprint as following:
lstFileNames = []
for i, content in enumerate(lstHtmlContent):
repName = 'report'+ str(uuid.uuid4()) + '.pdf'
lstFileNames.append("D:/Python/Workspace/" + repName)
HTML(string=content).write_pdf(target=repName,
stylesheets=[CSS(filename='/css/bootstrap.css')])
all files names, with paths, are saved in lstFileNames.
2. Create a zip file with pdf files generated by weasyprint
for this I'm using zipfile
zipPath = 'reportDir' + str(uuid.uuid4()) + '.zip'
myzip = zipfile.ZipFile(zipPath, 'w')
with myzip:
for f in lstFileNames:
myzip.write(f)
3. Send zip file to client for download
resp = HttpResponse(myzip, content_type = "application/x-zip-compressed")
resp['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'
4. Open file for downloading via Javascript
var file = new Blob([response], {type: 'application/x-zip-compressed'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
Problems
1. While the zip file is successfully received at front end, after I try to open it, it gives the following error:
The archive is in either unknown format or damaged
Am I sending the file wrong or is my Javascript code the problem?
2. Is there a way to store all pdf files in list of byte arrays and generate zip files with those byte array and send it to the client? I tried that with weasyprint but the result was same damaged file.
3. Not exactly a problem but I haven't been able to find it in weasyprint docs. Can I enforce the path to where the file should be saved?
Problem # 1 is of extreme priority, rest are secondary. I would like to know if I'm doing it right i.e. generating pdf files and sending their zip file to client.
Thanks in advance.
A slightly different approach would be to move the zip file to a public directory and then send that location to the client (e.g. json formatted), i.e.:
publicPath = os.path.join('public/', os.path.basename(zipPath))
os.rename(zipPath, os.path.join('/var/www/', publicPath))
jsonResp = '{ "zip-location": "' + publicPath + '" }'
resp = HttpResponse(jsonResp, content_type = 'application/json');
Then in your client's javascript:
var res = JSON.parse(response);
var zipFileUrl = '/' + res['zip-location'];
window.open(zipFileUrl, '_blank');
'/' + res['zip-location'] assumes that your page lives in the same folder as the public directory (so http://example.com/public/pdf-files-123.zip points to /var/www/public/pdf-files-123.zip on your file system).
You can clean up the public directory with a cron job that deletes all the .zip files in there that are older than an hour or so.
Once you have exited the with block the filehandle is closed. You should reopen the file (this time with open) and use read() to pass the contents to HttpResponse instead of passing the filehandle itself.
with zipfile.ZipFile(zipPath, 'w') as myzip
for f in lstFileNames:
myzip.write(f)
with open(zipPath, 'r') as myzip:
return HttpResponse(myzip.read(), content_type = "application/x-zip-compressed")
If that works, then you can use a StringIO instance instead of a filehandle to store the zip file. I'm not familiar with Weasyprint so I don't know whether you can use StringIO for that.

How do I save a text file using an InDesign script?

I'm extracting some data from an InDesign INDD file using a script. I'd like to save my data in a txt or json file, but my file is not saving successfully.
var data = 'string of data';
var filename = 'CS111.json';
var file = new File(filename);
var path = file.saveDlg(); //returns a valid path, but with spaces as '%20'
file.changePath(path);
var write = file.write(data); //returns false
file.close();
What am I missing here? The file doesn't show up in the chosen folder.
There are at least four steps in saving a file using InDesign Javascript: get a path and filename, create a file object, open the file, write to the file, and close the file.
I find that the write step will sometimes fail if I don't set the encoding.
//Define path and file name
var path = '~/Documents/';
var filename = 'filename.txt';
//Create File object
var file = new File(path + filename);
file.encoding = 'UTF-8';
file.open('w');
file.write('data here');
file.close();
Documentation: File class, .open(), .write()

Categories

Resources