Problem opening downloaded zip file using javascript - javascript

I am trying to open a downloaded a zip file sent to me against a GET request. I am using axios for my api requests.
PROBLEM
File is downloaded. But I am not able to extract or open it. Empty archive issue.
What I am using?
This is my response handler:
const data = response.data
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `report.zip`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
The API works fine. Tested with Postman. Able to download and work with files within that zip.
The above code works fine for csv file type.
I suspect that Blob thing. Please share what could be the problem.

I'm not 100% sure, but maybe you're just missing the type for the blob. This is the function I'm using to download files with Ajax. There's also a special path for Internet Explorer/Edge, because it will block the synthetic link click.
const downloadFile = (data, filename, type = "application/zip) => {
const blob = new Blob([data], { type })
if(navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob,filename)
} else {
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
So you can use it in your code:
const data = response.data
downloadFile(data, "report.zip")

Related

How to render blob in iframe and pass JWT token React

I need to add a preview function of word documents to my app. I have read that it is possible inserting like this:
<iframe class="doc" src="https://docs.google.com/gview?url=MyURl&embedded=true"></iframe>
the problem is that i need to pass JWT token to load files and when i download files it looks like:
const link = document.createElement('a');
link.href = url;
console.log(url, link);
link.setAttribute(
'download',
resultFileName,
);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
my url looks like:
blob: http://....
preview of images:
const url = window.URL.createObjectURL(blob);
let tab = window.open();
tab.location.href = url;
My question is how can I render blob object with passing JWT token in iframe. Thank you in advance

Convert Buffer to PDF

I am building a PDF using Puppeteer on the server and returning it as a Buffer to the client for download. I can't figure out why this conversion is not working for download. If I download it on the server side, everything works fine. Where am I going wrong?
onSuccess(data) {
const blob = new Blob([data as Buffer], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'test.pdf'
link.click()
},
This always happens, I figure it out right after posting.
The answer is nuanced. I'm using React Query to get the data. The Buffer coming back from Node and Puppeteer looks like:
{ type: Buffer, data: [...] }
The data to convert is on the data property, not the Buffer itself. So the correct code looks like this:
onSuccess(data) {
const blob = new Blob([data.data as Buffer], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'test.pdf'
link.click()
},
This felt hacky (and made TS upset) so I kept searching and decided to convert the PDF to base64 before returning to client and that seems be working as well. On the server that looks like:
const pdf = await page.pdf()
const base64 = pdf.toString('base64')
return `data:application/pdf;base64,${base64}`

Can't download while connecting to the server on my network while on the phone

quick question.
So this is the code:
export const downloadImage = async (state) => {
try {
let response = await axios.get(state.url, {
responseType: "blob",
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", state.url.slice(18));
document.body.appendChild(link);
link.click();
} catch (err) {
console.log(err);
}
};
EDIT: Don't mind the slicing in the setAttribute and the state gives me the full info about the pic, url, text etc.
It works prefectly, when i click download it downloads the img.
Since im using react when i do npm start it starts the live server and when i try to connect to it through my phone (which is on the same wifi network), and i connect with my IPv4 address and react port number (Example: 182.1281.12:3000) the image wont download...
So even tho the code is the same, it works on my PC and won't on my Phone, why is that?
Thanks.

pdf file corrupt after downlod in react js

Unable to request service with blob content-type by REST API (GET), the file goes corrupted, below is a snippet that I used to get get the file.
PDF File is retrive from docware
while checking the downloaded pdf file size is less than the original file from the server and it was corrected.
handleDownload(url,fileName){
var element = document.createElement("a");
var file = new Blob([url], { type: "application/pdf", });
element.href = URL.createObjectURL(file);
element.download = fileName;
element.click();
}

Unable to download a file from S3 by the URL in a browser

I have such code snippet that used to be work with the previous versions of Google Chrome, but now it does not work. When I run this script I redirected to the page with the content of the file(it's a text) and with AWS URL(the same as in setAttribute).
var element = document.createElement('a');
element.setAttribute('href', 'https://s3-us-east-1.amazonaws.com/XXX/XXX/XXX?Signature=XXX&Expires=XXX&AWSAccessKeyId=XXX');
element.setAttribute('download', 'filename.txt');
document.body.appendChild(element);
element.click();
How to download this file?
I made an error in the comments.
Chrome still favours download attribute, but it completely ignores it if the anchor element has cross origin attributes ( meaning, if the file is hosted on a different domain).
To be able to download it, file needs to be served with header: Content-Disposition: attachment;
Check this tutorial to see how to set Content-Disposition in s3 management console: http://iwantmyreal.name/s3-download-only-presigned-upload
Here is my solution:
let downloadImage = url => {
let urlArray = url.split("/")
let bucket = urlArray[3]
let key = `${urlArray[4]}/${urlArray[5]}`
let s3 = new AWS.S3({ params: { Bucket: bucket }})
let params = {Bucket: bucket, Key: key}
s3.getObject(params, (err, data) => {
let blob=new Blob([data.Body], {type: data.ContentType});
let link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=url;
link.click();
})
}
The url parameter refers to the full url of the image.

Categories

Resources