How to combine multiple video blobs in js without gap? - javascript

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);

Related

Create XLSX file from file contents from server and save it

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();

Cannot change csv file charset to windows-1251

I try to create a button that would download a csv file. I have to make the file using windows-1251 charset.
But no matter what I do the file ended up in utf-8. Right now I'm trying something like:
async createCsv(result) {
const arrData = result.data
const aliases = result.aliases
let csvContent = [
Object.keys(arrData[0]).map(item => aliases[item]).join(";"),
...arrData.map(item => Object.values(item).join(";"))
]
.join("\n")
.replace(/(^\[)|(\]$)/gm, "");
const data = new Blob([csvContent], {
type: "text/csv;charset=windows-1251;"
});
const link = document.createElement("a");
link.setAttribute("href", URL.createObjectURL(data));
link.setAttribute("download", (new Date).toLocaleString() + ".csv");
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
And the file is in utf-8.
Is there a way to change the charset?
looking for the same last day.
that's the answer that really works
blob with conversion to 8bit cp1251 or cp1252
in my project ends up with the following
import * as iconv from 'iconv-lite'
let outdata = this.bankf.getOutputFile();
const encoded = iconv.encode (outdata,'win1251');
var file = new Blob ([encoded], {type: 'text/plain;charset=windows-1251'});
var link = document.createElement("a");
var url = URL.createObjectURL(file);
link.setAttribute("href", url);
link.setAttribute("download", "filename.txt");
document.body.appendChild(link);
link.click();
setTimeout(function() {document.body.removeChild(link); window.URL.revokeObjectURL(url); }, 0);
still looking for other solution as iconv brings around 400kb code , but for now. at least it works

PDF is blank when downloading using javascript

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

File download a byte array as a file in javascript / Extjs

In my Ext Js solution I am calling a service which is returning this JSON format
{"success":true,"filename":"spreadsheet.xlsx","file":[80,75,3,4,20,0,...(many more)]}
How can I make a file download dialog with the filename and the content of the byte array (file) ?
UPDATE
So I found this bit to start the downlaod
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(data.file, { type: 'application/octet-stream' }));
a.download = data.filename;
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
So far good
But the file I get is corrupted so I suspect I need to Encode/Decode the file variable?
I had to convert the file into a Uint8Array before passing it to the Blob
var arr = data.file;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
a.download = data.filename;
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
Reading this answer helped a lot https://stackoverflow.com/a/16245768/1016439
Building on Jepzen's response, I was able to use this technique to download a document from AWS S3 from within the browser. +1 Jepzen
s3.getObject(params, function(err, data) {
if (err === null) {
var arr = data.Body;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
a.download = fName; //fName was the file name portion of the key what was passed in as part of the key value within params.
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
} else {
result = 'failure'
console.log("Failed to retrieve an object: " + err);
}
});

Saving a Uint8Array to a binary file

I am working on a web app that opens binary files and allows them to be edited.
This process is basically ondrop -> dataTransfer.files[0] -> FileReader -> Uint8Array
Essentially, I want to be able to save the modified file back as a binary file. Ideally as a file download with a specified file name.
There doesn't seem to be any standard method of doing this, and that sucks, because everything up to that point is well supported.
I am currently converting the array to a string using String.fromCharCode(), base64 encoding that, and using a data uri in a hyperlink like data:application/octet-stream;base64,.., along with the download attribute to specify filename.
It seems to work, but it's quite hacky and I think converting the raw bytes to a string might introduce encoding issues depending on the byte values. I don't want the data to become corrupt or break the string.
Barring that, is there a better/proper method for getting an array of bytes as a binary file to the user?
These are utilities that I use to download files cross-browser. The nifty thing about this is that you can actually set the download property of a link to the name you want your filename to be.
FYI the mimeType for binary is application/octet-stream
var downloadBlob, downloadURL;
downloadBlob = function(data, fileName, mimeType) {
var blob, url;
blob = new Blob([data], {
type: mimeType
});
url = window.URL.createObjectURL(blob);
downloadURL(url, fileName);
setTimeout(function() {
return window.URL.revokeObjectURL(url);
}, 1000);
};
downloadURL = function(data, fileName) {
var a;
a = document.createElement('a');
a.href = data;
a.download = fileName;
document.body.appendChild(a);
a.style = 'display: none';
a.click();
a.remove();
};
Usage:
downloadBlob(myBinaryBlob, 'some-file.bin', 'application/octet-stream');
(shorter) ES6 version of the top answer:
const downloadURL = (data, fileName) => {
const a = document.createElement('a')
a.href = data
a.download = fileName
document.body.appendChild(a)
a.style.display = 'none'
a.click()
a.remove()
}
const downloadBlob = (data, fileName, mimeType) => {
const blob = new Blob([data], {
type: mimeType
})
const url = window.URL.createObjectURL(blob)
downloadURL(url, fileName)
setTimeout(() => window.URL.revokeObjectURL(url), 1000)
}

Categories

Resources