readAsDataUrl converting to octet-stream instead of pdf - javascript

I am getting a blob data from a RESTFul endpoint and then I need to convert it to base64 string with file type as application/pdf however its converting it to application/octet-stream.
Here's what my codes does:
const getBytesData = () => {
if (user) {
getInvoicePDFStringByInvoiceId('129', user.user.token).then((data) => {
if (data.blob) {
const reader = new FileReader();
reader.readAsDataURL(data.blob);
reader.onloadend = () => {
var base64data = reader.result.replace('octet-stream', 'pdf');
console.log('Pdf loaded:- ', base64data);
setPDFLoaded(base64data);
return;
};
} else {
console.log('Error happened from API = ', data.error, data.message);
}
});
}
};
Can someone help me understand what could solve this issue?

Related

Getting pdf file from from express and treating it as if it from an input

i am trying to make a component that take a pdf from input or an already uploaded one and then extract pages from it and uploaded again
when choosing a file from input (choosing file from my computer)
i am using this
const handleFileChange = async (event) => {
const file = event.target.files[0];
setFiles(event.target.files[0])
const fileName = event.target.files[0].name
setFileName(fileName);
const fileReader = new FileReader();
fileReader.onload = async () => {
const pdfBytes = new Uint8Array(fileReader.result);
const pdfDoc = await PDFDocument.load(pdfBytes);
setPdfDoc(pdfDoc);
setPdfBlob(pdfBytes)
};
fileReader.readAsArrayBuffer(file);
setShowPdf(true)
};
we get a pdfDoc and a Unit8Array
then i use the pdfDoc to get pages and extract a new pdf file....
this works fine
now when selecting a file that we already uploaded
i use this to ping the api to get the file
const handleGetFile = async (url) => {
const headers = {
Authorization: "Bearer " + (localStorage.getItem("token")),
Accept: 'application/pdf'
}
await axios.put(`${process.env.NEXT_PUBLIC_API_URL}getPdfFileBlob`, {
pdfUrl: `https://handle-pdf-photos-project-through-compleated-task.s3.amazonaws.com/${url}`
}, { responseType: 'arraybuffer', headers }).then((res) => {
const handlePdf = async () => {
const uint8Array = new Uint8Array(res.data);
const pdfBlob = new Blob([uint8Array], { type: 'application/pdf' });
setPdfBlob(uint8Array)
// setPdfDoc(pdfBlob) .....? how do i create a pdf doc from the unit8array
}
handlePdf()
}).catch((err) => {
console.log(err)
})
}
this the the end point i am pinging
app.put('/getPdfFileBlob',async function(req,res){
try {
console.log(req.body.pdfUrl)
const url =req.body.pdfUrl;
const fileName = 'file.pdf';
const file = fs.createWriteStream(fileName);
https.get(url, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
// Serve the file as a response
const pdf = fs.readFileSync(fileName);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader( 'Content-Transfer-Encoding', 'Binary'
);
res.setHeader('Content-Disposition', 'inline; filename="' + fileName + '"');
res.send(pdf);
});
});
} catch (error) {
res.status(500).json({success:false,msg:"server side err"})
}
})
after getting this file here is what am trying to do
const handlePageSelection = (index) => {
setSelectedPages(prevSelectedPages => {
const newSelectedPages = [...prevSelectedPages];
const pageIndex = newSelectedPages.indexOf(index);
if (pageIndex === -1) {
newSelectedPages.push(index);
} else {
newSelectedPages.splice(pageIndex, 1);
}
return newSelectedPages;
});
};
const handleExtractPages = async () => {
for (let i = pdfDoc.getPageCount() - 1; i >= 0; i -= 1) {
if (!selectedPages.includes(i + 1)) {
pdfDoc.removePage(i);
}
}
await pdfDoc.save();
};
well in the first case where i upload the pdf file from local storage i get a pdfDoc
console of pdf Doc and pdfBlob
and when i select already existing file i can't find a way to transfer unit8array buffer to pdf doc
log of pdfBlob and no pdf doc
what i want is transform the pdfblob to pdfDcoument or get the pdf document from the array buffer so i can use getpages on it

How can I send an image represented as base64 encoding to a Python server using ReactJS? [duplicate]

This question already has answers here:
ReactJS base64 file upload
(2 answers)
Closed 2 months ago.
React js antd upload component send image base64 to the python server
Image upload send to the server base64
Without using formData method
Try this one
Please refer antd doc for uploading.
https://ant.design/components/upload
handleChange= (info: any) => {
let fileList = [...info.fileList];
fileList.forEach(function (file, index) {
let reader = new FileReader();
reader.onload = (e) => {
file.base64 = e.target.result;
};
reader.readAsDataURL(file.originFileObj);
});
this.setState({ fileList });
};
You need input type="file" to select an image:
<input
type="file"
onChange={onChange}
/>
Function to convert file to base64:
const convertBase64 = (file) => new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.readAsDataURL(file)
fileReader.onload = () => {
resolve(fileReader.result)
}
fileReader.onerror = (error) => {
reject(error)
}
})
And onChange handler:
const onChange = async event => {
const file = event.target.files[0]
const base64 = await convertBase64(file)
const formData = new FormData()
formData.append('file-key', base64)
// --- now you can send base64 file to server --- //
await fetch('api/{your-api-here}', {
method: 'POST',
body: formData,
})
}

Is it possible to convert a blob file into a base64Data in Javascript (Ionic,Angular)?

[
async FileZip() {
const code = await fetch("./assets/input.txt")
var blob = await downloadZip([code]).blob()
console.log(blob);
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
FileSharer.share({
filename: "input.zip",
base64Data: //base64datawillbehere ,
contentType: 'application/zip'
});
reader.readAsDataURL(blob);
})
I am pretty new to Ionic and App Development.
I have compressed a text file into a zip blob file using client-zip library. Using the downloadZip() I am getting a zip blob file like this.
I want to share this file as a zip file using Capacitor Filesharer . But to use this Filesharer plugin , it seems I have to convert this blob zip file into base64 data.
Can anyone tell how to do it ?? Or is it even possible to do this ??
Please forgive me If you find my question too immature ,because as I said I am pretty new to javascript .
Consider using the following function:
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
reader.readAsDataURL(blob);
})
}
Try modifying your code as demonstrated below: (haven't changed the previous answer as it might be useful for others to implement such operations using Observable strategy unlike your case where I would recommend of using Promise)
ngOnInit(): void {
this.fileZip();
}
private blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onabort = reject;
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
})
}
private async fileZip(): Promise<void> {
const code = await fetch("./assets/input.txt")
const blob = await downloadZip([code]).blob();
const base64Data = await this.blobToBase64(blob);
await FileSharer.share({
filename: "input.zip",
base64Data: base64Data,
contentType: "application/zip",
})
}
You can try this code -
fileZip() {
constcode = awaitfetch("./assets/input.txt");
varblob = awaitdownloadZip([code]).blob()
console.log(blob);
varreader = newFileReader();
reader.readAsDataURL(blob);
reader.onloadend = ()=> {
constresult = reader.resultasstring;
constbase64Data = result.split(',')[1];
console.log(base64Data)
FileSharer.share({
filename:"json.zip",
base64Data,
contentType:'application/zip'
});
}
}

Pako not able to deflate gzip files generated in python

I'm generating gzip files from python using the following code: (using python 3)
file = gzip.open('output.json.gzip', 'wb')
dataToWrite = json.dumps(data).encode('utf-8')
file.write(dataToWrite)
file.close()
However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):
this.http.get("output.json.gzip")
.map((res:Response) => {
var resText:any = new Uint8Array(res.arrayBuffer());
var result = "";
try {
result = pako.inflate(resText, {"to": "string"});
} catch (err) {
console.log("Error " + err);
}
return result;
});
But I'm getting this error in the console: unknown compression method. Should I be doing something else to properly inflate gzip files?
Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer:
return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob }))
.map((res:Response) => {
var blob = res.blob();
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function() {
arrayBuffer = this.result;
try {
let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"});
let obj = JSON.parse(result);
console.log(obj);
} catch (err) {
console.log("Error " + err);
}
};
fileReader.readAsArrayBuffer(blob);
return "abc";
});

Reactjs - Can't base64 encode file from react-dropzone

I am using react-dropzone to handle file upload on my website. When successfully loading a file, the dropzone triggers the following callback:
onDrop: function (acceptedFiles, rejectedFiles) {
myFile = acceptedFiles[0];
console.log('Accepted files: ', myFile);
}
I would like to base64 encode this file. When doing :
var base64data = Base64.encode(myFile)
console.log("base64 data: ", base64data) // => base64 data: W29iamVjdCBGaWxlXQ==W29iamVjdCBGaWxlXQ==
Regardless of file uploaded, it always prints out the same string.
Am I missing something ? I need to base64 encode this file (always images)
This JS Bin is a working example of converting a File to base64: http://jsbin.com/piqiqecuxo/1/edit?js,console,output . The main addition seems to be reading the file using a FileReader, where FileReader.readAsDataURL() returns a base64 encoded string
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
If you want it in a neat method that works with async / await, you can do it this way
const getBase64 = async (file: Blob): Promise<string | undefined> => {
var reader = new FileReader();
reader.readAsDataURL(file as Blob);
return new Promise((reslove, reject) => {
reader.onload = () => reslove(reader.result as any);
reader.onerror = (error) => reject(error);
})
}

Categories