How to convert file from URL to base64 on NodeJS? - javascript

I'm trying to retrieve an image (or file), then convert it to base64 on Nodejs.
I don't want to download and save the file. I've tried this:
const fileURL = "https://media.istockphoto.com/vectors/sample-sign-sample-square-speech-bubble-sample-vector-id1161352480?k=20&m=1161352480&s=612x612&w=0&h=uVaVErtcluXjUNbOuvGF2_sSib9dZejwh4w8CwJPc48=";
const file = await httpPromise({
uri: fileURL,
method: 'GET'
});
const base64 = new Buffer(file).toString('base64');
console.log(base64);
But this doesn't work. How can make it?

Related

How to upload a client PDF file object to the pdf-lib JavaScript library

I have looked at the pdf-lib website and do not see any example to load a PDF using an "input file" on the client side. All examples points to a URL to load a PDF. Is it possible to pass a file object to the function that reads the PDF instead of a URL?
const formPDFBytes = await fetch(url).then(res => res.arrayBuffer())
const pdfDoc= await PDFDocument.load(formPDFBytes );
I think if we can somehow set the file object as an array buffer to formPDFBytes, that may do the trick.
[From OP comments]
The user is the one who has the PDF and loads it via the DOM input file dialog. So nothing here would be sent to the server and the entire PDF parsing operation is done by the client.
According to pdf-lib's code, the PDFDocument.load function accepts in the first argument a string | Uint8Array | ArrayBuffer.
If you want to read a file locally, you can do this:
import fs from 'fs'
const uint8Array = fs.readFileSync('/path/to/myFile.pdf')
const pdfDoc3 = await PDFDocument.load(uint8Array)
if you want to load the file from the <input type="file" /> element,
you need firstly to read the file as ArrayBuffer.
<input type="file" id="file">
//
const file = document.getElementById('file').files[0]
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => {
const pdfDoc = await PDFDocument.load(reader.result);
//...
};

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.

Showing binary PDF in browser Javascript

I have a MSSQL Server Database with files stored as a column Content of type VARBINARY(MAX) in a SQL table.
I developed a backend Node.js server with Express.js to access the database. In this backend I have a route called /api/file/:id_file which takes the content of the file with id_file
async getFile(req,res){
const {id_file} = req.query
const file= await db.Files.findOne({
where:{
'Id': id_file,
}
})
res.contentType('application/pdf')
res.send(file.Content)
}
Then in frontend using Javascript, I have an iframe
<iframe id="view" src="" style='height: 500px; width: 1000px;' />
And I use an ajax request to get the file. When I have the response, I just convert it to blob and set the src attribute of iframe element with the base64 encoding of the blob
const reader = new FileReader();
reader.onload = () => {
const b64 = reader.result.replace(/^data:.+;base64,/, "");
$('#view').attr('src','data:application/pdf;base64,'+ b64);
};
reader.readAsDataURL(new Blob([resp.data], { type: "application/pdf" }));
When I try to request a file and show, I see a blank PDF, nothing is shown.
Am I missing any step to convert the content of the file to base64?
You don't need a filereader since you're not reading a file from the filesystem or user input; you already have the file pulled down from the API. If your binary pdf data is in resp.data then you just need to use btoa
creates a Base64-encoded ASCII string from a binary string
$('#view').attr('src','data:application/pdf;base64,'+ btoa(resp.data));

Blob type open more than one file type like pdf and jpeg

I want to preview a file in another browser tab by clicking on a file which I uploaded before.
It's working fine with {type:'application/pdf'} or {type: 'image/jpeg'} but I need both of them.
Is there a way to set more than one type for a Blob?
When i get the Dokument from the Backend I don't geht the type of the file. So I can't check either a File is pdf or a jpeg.
const fileOpen = new Blob([response], {type: 'image/jpeg' }); // this works fine!! but i need to open a pdf file as well.
const fileUrl = URL.createObjectURL(fileOpen);
window.open(fileUrl);
If response is a Fetch API Response object, you can set the type of Blob according to the type of response:
const fileOpen = new Blob([response], {type: response.data.type });
const fileUrl = URL.createObjectURL(fileOpen);
window.open(fileUrl);

Convert Excel to PDF programmaticaly

I am using 'exceljs' module in my Angular project to build an Excel file.
Instead of exporting it as Excel file, I would first like to convert it to PDF and then download it as such.
I can successfully export and save this file to my computer:
workbook.xlsx.writeBuffer().then((data) => {
console.log(data); // Uint8Array
console.log(data.buffer); // ArrayBuffer
console.log(new Blob([data])); // Blob
// code I use to export it as an Excel File
const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
const test = FileSaver.saveAs(blob, 'test.xlsx');
});
As written above, instead of an Excel file I would like to have it exported as a PDF file.
From the code you can see that 'exceljs' is giving me an Uint8Array stream of data, from which I can get out an ArrayBuffer, or I can convert it to a Blob.
I have tried using this without success:
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], { type: 'application/pdf' });
// or with 'application/octet-stream' type
// const blob = new Blob([data], { type: 'application/octet-stream' });
FileSaver.saveAs(blob, 'test.pdf');
});`
The PDF file gets exported, but it cannot be opened.
I get an error like "The file is corrupted."
Thank you for all the help in advanced.

Categories