I got Node JS server which gets XLSX file contents from metabase:
app.get('/channels', async (req, res) => {
// make request to metabase and take response as XLSX
const queryRequestURL = `${api}/public/card/${cardId}/query/xlsx?parameters=${params}`;
const result = got(queryRequestURL);
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader("Content-Disposition", "attachment; filename=file.xlsx");
return res.send(res);
});
It returns file contents like
So when i make request to server and receive response - it comes as file contents above.
I need to download this data as ordinary excel file on browser side.
What i've tried:
// make request with typical fetch and get result to res variable.
const filename = 'file.xlsx';
const file = new File(res, filename ,{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
// create link and click it virtually to download created file
var a = document.createElement('a');
a.href = window.URL.createObjectURL(file);
a.download = filename;
a.click();
But I'm getting the error:
Uncaught (in promise) TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence.
I think that I'm doing something wrong and there is more simple way to download file.
Without seeing how you're fetching, it's hard to know. But you should be able to use response.blob() to download the result.
fetch("${api}/channels}", {
method: "GET",
})
.then((response) => response.blob())
.then((blob) => {
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "file.xlsx";
document.body.appendChild(a);
a.click();
a.remove();
});
As Joey Ciechanowicz mentioned, we should return response.buffer() from backend and work with its data as blob at frontend.
I mean
NodeJS side (using Got):
const result = got(queryRequestURL, {
headers: headers
});
return await result.buffer()
Frontend side (pure JavaScript):
// fetch data
const result = await fetch(api + path);
return result.blob();
// download file
const filename = 'export.xlsx';
var url = window.URL.createObjectURL(result);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
a.remove();
Related
I have an array of urls. I download them with fetch and then get blob from each response with await res.blob(). I need to concat all these blobs together to make a full video out of it, I tried to push each blob into an array and make a file new File(blobArray, "test") but the result has a gap between each blob.
I've tried to save each blob as a separate file and concat them with ffmpeg -f concat -safe 0 -i text -c copy out3.mp4 and the result was perfect. So I know that my blobs are correct and the problem is how I am combining them together.
This is my full code:
(async function() {
var urlString = `
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18160.ts?Expires=1630841672&Signature=C-DrIcvmIGkm0s42EQRPWh6Y-aEWvnl2xu1LOIWyzgQqOe-~6E9rLtpR5Kdfz8lNdNXVFz2XyrsgSX1Dn8AUbxUM6umqxALPn57sdSUoVf5-JQce472EHX-roQTsy3SAM~IIXH3B6FHcpdce~1vdqTze~nQY2F3wbzCPyspJSEPU74~-TySj8PhHrFtYNFIsFVr4R-Pc4FF-EWy2zXzo0Av59-4VlOXqFYhmQwcm~kimWNXJpOYhghv6pVbFYzyp7x9tYLiX1~9hbTG3otmoBAJGRt7EUlZiBZhprAgMzhrPS2TezenBKXNf0qJEp-fnC5so0OykRt-TGhyRapbJoA__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18161.ts?Expires=1630841672&Signature=bBVrS4brV209hRADZgPnYQICBcXWe6Ed6zwBOFdozjIR1tiuahx3YmPhM8uaxLNRqowALgylen1wQBmdK5bGm~73DQUcUUfGXQU8kIv45CW1DyHDzX-ECR3MDpzSzIYDI8ELbFXK8gmT7ELgtmdkSrL0XO0FXCVAzLrzSw6-0XAZgzBY7tZUncRum5Wb7EhYQgluO2uCquz6HZqaVA9IYoCeFWKFXvU3xE-RBqHXksWkZO01o3UNEEgnzYrRepurcdYY029~6MsHEyj5304pDlefXKrEj8mbZidvhaUKkiIjcoG15jznWPvN3WAewK3zXpLlCYhBMuDL0kOVIq5zjA__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18162.ts?Expires=1630841672&Signature=a3lUizMPzmtntrapM9qLk0f~GrfnQAFNlEJEzrvFowGMZVMukqPVfloM7Z9J33ZThK7mKfRy7tiYH1KDzCT5hpRl0X-pcCvcmAmy4u8h1upKO0RJmaP1v7PVzqACPTyvDHNDy3Fh-pxhpO1ubKR2SR7gq1n1K6tX8sbogNHmo0jPnERRxtLKF618nAuGBPQVYofkNG0zvcomGRX7iN95ovn8Ql9IxmqsGLGI2HzlJq3v8L4iS6UYUpV4yhAtZxmbERACq82JcwdiMMlLlnn~SoenYttzDrTdSh-u321KqjAoD6lij6l~j-dReVWY4HTDlsCnGaw9w-eOIuEywi8DpA__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18163.ts?Expires=1630841672&Signature=Q6eYIsoPFVKYjY0vVDcnMKKI3oV14xnfDLpvJdH7Z9GoNqojPRXOyITTmd6Ed1JCxmF9oAkfvdghH0Ks1-fSYL3tvu5kMuJe2sWbeKCimqHQ89JvhJ3hOfVvUBIv-QVdbGYXD9FOr8T5s~HYC5KkDrFqRorDidH04y67P175sBXMtYIwt04KzG7m17X8kbJkjsjuVhD0sZ0ewACz1OBPnxO9qLdvGsRqVtW1FmuKSnDULieqdsQGfuH1YkkVCr7H4t0B5SF77vvxYkvcr4uGRjKMPVdggg3BYQKCWHn~pEEP2~P6oJZdfwbu9wnKJnIvimXVleHYW-hPk0OWBD5JAg__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18164.ts?Expires=1630841672&Signature=HItA9pW3RiIhf9pFFGm4Y8FmikCPXBfh8gxJVNSLsJ9cuDONLX3n26ZjYO2NaROwsID9YjxwlDuS9jqqe62A7vLPsAjVmL6WvCZ8a22tAihPBPM-qOSWoHS7E~3bSurc9CzkQwlOBvg01~Mjl-E2kvP-hn0FxhTPk1FAE8BrL6DIeGKsBqIdvVgHsJyTi9osDNPG~OtKRKRskAK37QcXidkiLjFMcbX6uqwmcVHEpP30fDj13wBMwx2suuJ27~ICmSH44CHCuRcKujISKbrVjbnsUw4ivA7a72hyybSTDhwZBzjj753FFy0LqSVWVFOJJY1HXEnZ4mpvax9N1lth2Q__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18165.ts?Expires=1630841672&Signature=L4T1BtTtHVM7p2JqvXEXLcJDUNdm8IZ8LU-oPkKxYBwuZHXEdxOLTTrFSX-3N39c7JMWDljWNi2bLrjbjK2xa1yMB5eTjvZTjusJDPk91RW0cMB4qsTpuXR1ui~ybPe5ABoV6N4cUXj~bUQFfUURo66kH5UdC~SIKMzQx59mnATvKZfZwOizm2kEuc8qaXPi9yJmYdPGhr6qSN1~kl0NEWciOU3o-etMtFc29yrlGl~Fgj0bvCyAwLwtR4yQwKFHCJWZPiMfJky9GJB4LKcyKBFu7bkDjk2BzOveJklvIPF~tZKkd3ki~I5kfYhTL-~hEDT4i9hIfHJEF1JF1rf~bw__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18166.ts?Expires=1630841672&Signature=Kzf38iYJwebZG2nzkrPSVEvqWxSc959XcvUqiMhZC1lFwZefNTMw1a5EHcUfObujy~3XQ3Yxm-Ls8CziLLvO3Vi8wEg05GB1COnFT1hxasQHID1tmMaXrKrRBZp2XZApehhOpSroJdx46Zb8qlM4JMu3lf30eBIHsbPOIsdmW1o2E9USZUMUKiG-T3feO1kjT3scDsoKcaX2cQrqE8c1oAuEy57eASgFKQcy0OGtrxDujPHLNWYmRv~CFZxHf8LCuMKBrL9OtXE7py0g9x4d4BvwzQ5XOoQ5d5JsfnT8EeH5Lqbh8crtauJb5BrUk6j9uV1MWviZi7WQzGcds6eItg__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18167.ts?Expires=1630841672&Signature=Vc5mVh~J-WEG2eHhiXnsNFBI~kpCtTnwwgiihaP6Fvm1IeA7eJ0QzA5g2Tq1VADLI-B2Bl1Ss~CmSyyXQEiM~IxRVjiNs1~PpnIKm0gFD0iBgIZOS3GoS6bx4bkRiy1tEMn98~~1VGqZ4FxJxc59QOdjmwvAvUvGN01zojOHt0i61XDqjeLz~wFUR9MVh~QYskV4w5sR~THYpKqiMej6JAIVz3avhadVlE1p0P9Gel7LLo59WjFx3Da1huQzBNQ2B8l3-pQpepwbiI0vsrN09aZHLnVtu1NPeEbpG5lZMIhYLay5qQTg1d87ouDoZ8zWYl0buPu5ZL06DiBFIDDhrA__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18168.ts?Expires=1630841672&Signature=QsdnxTFnRVml4yq~cbIMRDdESRoX6KH2AkCCm5J-MqW3QEr9RQU5Y7v41nKxIo~IgwI9FMoTRSk61whNyrLePlw2GXq38iK6UhlmpMkJYF3Tvj84GDckbpdqrIQLlZRJPngjx9n2eE3R8Sb7igXwIrr5dymYjEh2Hb0jkYs0~9Zfzr-pJAGoEdUr36hkGP2UXP4n~atb1cDW1hDbd8YJeUNYfKfTSPwq5~E9Te9P674pL2D~WutSM-Gk9xXMhVX7Z0VJWKQh5JWzSkrzDTc9rjTnotWJ7~kU1HqapqD2eVr3DOwI2b19Yv7FGWD3wrxtLA9A8AhkEbpaHLcuYyIS9w__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e18169.ts?Expires=1630841672&Signature=e-uHBmY7DMqAkrpRbtfyiRlglUU9wwLY5d2Oar44~xgQerrV~5dAa7q~Nf3V2WNyi22Bg88f4bvjYMIPMjghT4aZol7JXv1Q7VH~1xjydJfaIEXunOZzqswi4PbljlXui7W0c2c59hj~6c96bc6Iyr79x3bvylA1nnxJo2Y6a1Zus0irS7u-45BjXym27NtXrhOwpcVc2GNXhI74yqjXA-vFr1XVuHBHMQVMLTryYlStwoAUXnn7K~U88skq0ursQqpDFCmlDkgoXED~rdm7THJht9wOhkFbf2T79xsENBhPoiS56DLT7qIemBFGDUxHVeoTgZdMLXE2SVsgp-LBmQ__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e181610.ts?Expires=1630841672&Signature=KFxUkMZhteXsl3mSobA5Xg5~PQIztGtmgd~E1g2peja~oHMPNUWE6ihhcOEkO1M6CKXDycegq9~8xv6GqWSrRz5xntTYXNWyRT2-C0W2E79E0Fd1QLndb1~UP1uq~6z-8FbxXLIhHgCzSgaVtPxt8vFqQ1TI-Zd0j0ramKvfWu4iZiZTxEWn5d5Iaaf-LqTdgXWUKqWsr6F0czH7FZh6sI4NVmUAOOD1-sez5ALVr8GBruihB23W5E2yOWtk31KTC-M7TVf1AjwQTJurm~rWka4~~c2lCJ~~o-n~N5p38KdaReZWk2yCqHRYt7pdwpyqIAhosvsVs8Kf5AT2mQV-tQ__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e181611.ts?Expires=1630841672&Signature=AZuneobcwantsOflRrRO4DJzmW0JzqOcDDrB8YKIh~YbL5AuhlZV2OyN6fgUJ0~EVAqRk4h2RpUmZiD4ov8muNu3U-SHp1ksHia3d8cct7Ns485ta87Lb6GqX9yvF3qTNCTT3f5FSQeoKPmGXWPpbzUsdC7TGxNVy8M5IcdqHeoJDrOUeYOqnyQtNDrhWzFsp14YL4RqWBoiz0llpN6w-8QfaeWzCYkT~KxM0UKlPFDzeijXcNJS-tjCxUrT9CnYZ3IfMDvufDCfztd20x37rK1xSln~fuF4PLsMdrfpayY1lSPMgmLP9-~k7SiYth4qSU4CsdgY~1HTZJpUHg2AXQ__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
https://hls-c.udemycdn.com/2020-06-25_14-12-40-d54947f66bb66a48d9c119adf45739ad/1/hls/AVC_1920x1080_800k_AAC-HE_64k/aa0003ab30f349f2a87b8a745d2b648e181612.ts?Expires=1630841672&Signature=Dcl1pJwVlfyN-Lqlq8RruR4t4c3l6Y~hSXPdZyLcspdg16gH-Jk78buQCD2LEniYF6xgXRVRgdLQj26lxiHJi2LiHXHV8~jKQVVrU2lnga9p48M35KdJZheJ~N6f91hsTpHEhYBBSR0TYhRcTMrh1WXstOMW5kHA01nVzq3mOpnHlDFpcHNuTslTAAouqeMXsdY6H4ta15puQcVnvqchOr-7c5dU4ZG14FtHF2WvjnMEWARWDvivOvoqQAqwPQgHm5SxJFw~qyZmIeRUG-TT9i-RXIAzSivg6vKiP2A-AomTOwGW3oFRXKLdMXSMlcd6lmQ7~b7jTi7uNX4Bhup-jQ__&Key-Pair-Id=APKAITJV77WS5ZT7262A,
`
const urlArr = urlString.split(",")
let blobArr = [];
for(let url of urlArr) {
if(url) {
try{
const res = await fetch(url);
const blob = await res.blob();
blobArr.push(blob)
} catch (err) {
console.log(err)
}
}
}
const newBlob = new Blob(blobArr)
const finalFile = new File([newBlob], "test-udemy");
const a = document.createElement("a")
const url = URL.createObjectURL(finalFile);
a.href = url;
a.download = "test-udemy";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
})()
Unfortunately links will expire soon but I think it is obvious what I am trying to do.
So Is there any way to cancat blobs in JS and create the entire video smoothly like the ffmpeg does?
Thanks in advance.
try to create and download the blob like this, you can safely omit the file creation:
let blob = new Blob( blobArr, {
type: "video/mp4",//your own type here
});
let url = URL.createObjectURL(blob);
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = "PRUEBA.webm";//your own name here
a.click();
window.URL.revokeObjectURL(url);
I am trying to make a JavaScript/HTML local webpage that just gets opened from my local computer's files. I would like to make it save data in JSON form. But I've been having trouble finding out how to make a local JavaScript program read and write to a file in its same directory.
You can not write files to the local machine if you're using Javascript in the browser.
But you can download the JSON file to your local machine using Blob
You can use this code:
const data = {
key: "value"
};
const fileName = "data.json";
const saveFile = (() => {
const a = document.createElement("a");
document.body.appenChild(a);
return (data, filename) => {
const json = JSON.stringify(a);
const blob = new Blob([json], { type: "application/json" });
const url = window.URK.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
})
saveData(data, fileName);
I have a link /api/ticket/1/download to my server and if I copy paste it into the browser, it will start a download of my file with it's filename extension and everything set up already.
How can I do it in javascript? With thymeleaf i was just using <a href="myLink"> and it worked like if I paste it in the browser. But due to react-router a href just goes to another page.
But if I use await fetch like this:
let url1 = '/api/ticket/' + fileId + '/download';
const response = await fetch(url1);
const blob = response.blob();
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `file.jpg`);
document.body.appendChild(link);
link.click();
i can transfer response into blob, but then i miss the files name and extension.
The only way to solve this that i found is: send file name and extension in a response header and than parse them manualy.
like:
in spring:
myControllerMethod( HttpServletResponse response){
...
response.setContentType(att.getType());
response.setHeader("Content-Disposition", "attachment; filename=\"" + myFileName + "\"");
}
in react:
const headers = response.headers;
const file = headers.get("Content-Disposition");
and then parse manully this 'file' to get filenamel;
Try in this way, it may help you :
fetch('http://localhost:8080/employees/download')
.then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'employees.json';
a.click();
});
For more reference you can go through This link
I'm downloading a file from a server. There I'm setting a file name which I would like to read on a frontend. Here is how I'm doing it on server:
string fileName = "SomeText" + DateTime.UtcNow.ToString() + ".csv";
return File(stream, "text/csv", fileName);
Basically I will return different types of files, sometimes csv sometimes xlsxand sometimes pdf. So I want to get filename on a frontend so I might save it as it should be for example SomeText.pdf it will be saved automatically on local machine as pdf.
Here is my frontend code:
getFileFromServer(params).then(response => {
console.log('server response download:', response);
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });
//const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.xlsx'; // Here I want to get rid of hardcoded value instead I want filename from server
link.click();
link.remove(); // Probably needed to remove html element after downloading?
});
I saw in Network tab under Response Headers that there is a Content-Disposition which holds that info:
Content-Disposition: attachment; filename="SomeText22/08/2019 10:42:04.csv";
But I don't know is it available in my response and how can I read it in my frontend part so I might replace
link.download = 'file.xlsx';
with Path from a server ..
Thanks a lot guys
Cheers
this is a special type of header so to get this header in frontend the backend person should allow from his end. then you can the headers in the response
response.headers.get("content-disposition")
the below code I have used in my project
downloadReport(url, data) {
fetch("url of api")
.then(async response => {
const filename = response.headers
.get("content-disposition")
.split('"')[1];
const text = await response.text();
return { filename, text };
})
.then(responseText => this.download(responseText))
.catch(error => {
messageNotification("error", error.message);
throw new Error(error.message);
});
}
You can get filename from Content-Disposition header by this way
getFileFromServer(params).then(response => {
// your old code
const [, filename] = response.headers['content-disposition'].split('filename=');
const link = document.createElement('a');
link.download = filename;
// your old code
});
Hope this will help
To get the filename from Content-Disposition on client side(frontend) you must give permission from server side(Backend). Spring users can use
#CrossOrigin(value = {"*"}, exposedHeaders = {"Content-Disposition"})
#Controller
#RequestMapping("some endpoint")
in their controller class.
Then from frontend we can get filename using.
const filename = response.headers['content-disposition'].split('filename=')[1];
Hope this helps. Above solution worked fine for me
I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written in UI is as follows:
$http.get('http://MyPdfFileAPIstreamURl').then(function(response){
var blob=new File([response],'myBill.pdf',{type: "text/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myBill.pdf";
link.click();
});
'response' contains the PDF byte array from servlet outputstream of 'MyPdfFileAPIstreamURl'. And also the stream is not encrypted.
So when I click the link, a PDF file gets downloaded successfully of size around 200KB. But when I open this file, it opens up with blank pages. The starting content of the downloaded pdf file is in the image.
I can't understand what is wrong here. Help !
This is the downloaded pdf file starting contents:
solved it via XMLHttpRequest and xhr.responseType = 'arraybuffer';
code:
var xhr = new XMLHttpRequest();
xhr.open('GET', './api/exportdoc/report_'+id, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:"application/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Report_"+new Date()+".pdf";
link.click();
}
};
xhr.send();
i fetched the data from server as string(which is base64 encoded to string) and then on client side i decoded it to base64 and then to array buffer.
Sample code
function solution1(base64Data) {
var arrBuffer = base64ToArrayBuffer(base64Data);
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([arrBuffer], { type: "application/pdf" });
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
var data = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
document.body.appendChild(link); //required in FF, optional for Chrome
link.href = data;
link.download = "file.pdf";
link.click();
window.URL.revokeObjectURL(data);
link.remove();
}
function base64ToArrayBuffer(data) {
var binaryString = window.atob(data);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
};
I was facing the same problem in my React project.
On the API I was using res.download() of express to attach the PDF file in the response. By doing that, I was receiving a string based file. That was the real reason why the file was opening blank or corrupted.
In my case the solution was to force the responseType to 'blob'. Since I was making the request via axios, I just simply added this attr in the option object:
axios.get('your_api_url_here', { responseType: 'blob' })
After, to make the download happen, you can do something like this in your 'fetchFile' method:
const response = await youtServiceHere.fetchFile(id)
const pdfBlob = new Blob([response.data], { type: "application/pdf" })
const blobUrl = window.URL.createObjectURL(pdfBlob)
const link = document.createElement('a')
link.href = blobUrl
link.setAttribute('download', customNameIfYouWantHere)
link.click();
link.remove();
URL.revokeObjectURL(blobUrl);
solved it thanks to rom5jp but adding the sample code for golang and nextjs
in golang using with gingonic context
c.Header("Content-Description", "File-Transfer")
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Content-Disposition","attachment; filename="+fileName)
c.Header("Content-Type", "application/pdf; charset=utf-8")
c.File(targetPath)
//c.FileAttachment(targetPath,fileName)
os.RemoveAll(targetPath)
in next js
const convertToPDF = (res) => {
const uuid = generateUUID();
var a = document.createElement('a');
var url = window.URL.createObjectURL(new Blob([res],{type: "application/pdf"}));
a.href = url;
a.download = 'report.pdf';
a.click();
window.URL.revokeObjectURL(url);
}
const convertFile = async() => {
axios.post('http://localhost:80/fileconverter/upload', {
"token_id" : cookies.access_token,
"request_type" : 1,
"url" : url
},{
responseType: 'blob'
}).then((res)=>{
convertToPDF(res.data)
}, (err) => {
console.log(err)
})
}
I was able to get this working with fetch using response.blob()
fetch(url)
.then((response) => response.blob())
.then((response) => {
const blob = new Blob([response], {type: 'application/pdf'});
const link = document.createElement('a');
link.download = 'some.pdf';
link.href = URL.createObjectURL(blob);
link.click();
});
Changing the request from POST to GET fixed it for me