File download does not work on firefox - javascript

I'm using angular 1.2.27, and I'm trying to download a file. It works perfect on chrome but on FF nothing happens, the request returns 200/ok and the success code runs, but that's it, no file is downloaded:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
var wurl = $window.URL || $window.webkitURL;
var fileURL = wurl.createObjectURL(file);
console.log( 'fileURL:' , fileURL );
var a = document.createElement("a");
a.href = fileURL;
a.download = fileName;
a.target = "_self";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
wurl.revokeObjectURL(fileURL);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}
The only difference i see is when i log the fileURL. on chrome it appears like this:
blob:http%3A//localhost%3A9000/e869aa88-8190-4d9d-a379-9ad977a09613
And on FF like this:
blob:http://localhost:9000/f36b7773-00bb-4ade-87be-8f197c41ccf8
But I assume this is just a console thing.
any idea what I'm doing wrong?

Putting an answer here for reference. Using FileSaver from #Satpal comment, i was able to solve it easily:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
saveAs(file, fileName);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}

Related

Generate Zip file contain list of Files without JSZip library

Hello Developers,
I'm trying to download the list of files getting form XMLHttpRequest() request method and store it in the array of files. I wanted to zip all the files in an array using javascript without using any 3rd party library.
I have tried to achieve this by URL.createObjectURL(url) and URL.revokeObjectURL(url) method but the file I'm getting is corrupted.
I'm Sharing my code snippet please help me out
const URLS = [
'https://vr.josh.earth/assets/2dimages/saturnv.jpg',
'https://vr.josh.earth/assets/360images/hotel_small.jpg',
'https://vr.josh.earth/assets/360images/redwoods.jpg'
];
$(document).ready(function () {
debugger
$("#downloadAll").click(function () {
var blob = new Array();
var files = new Array();
URLS.forEach(function (url, i) {
getRawData(url, function (err, data) {
debugger
var mydata = data;
// mydata = btoa(encodeURIComponent(data));
// var blobData = b64toBlob(mydata , 'image/jpg');
var blobData = new Blob([mydata], { type: 'image/jpg' });
blob.push(blobData);
var filename = "testFiles" + i + ".jpg";
var file = blobToFile(blobData, filename);
files.push(file);
debugger
if (files.length == URLS.length) {
// saveData(blob, "fileName.zip");
var AllBlobData = new Blob([blob], { type: 'application/zip' });
saveData(AllBlobData, "Test.zip");
// saveFile("DownloadFiles.zip", "application/zip", files)
}
});
});
});
});
//Retriving record using XMLHttpRequest() method.
function getRawData(urlPath, callback, progress) {
var request = new XMLHttpRequest();
request.open("GET", urlPath, true);
request.setRequestHeader('Accept', '');
if ('responseType' in request)
request.responseType = "arraybuffer"
if (request.overrideMimeType)
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send();
var file, err;
request.onreadystatechange = function () {
if (this.readyState === 4) {
request.onreadystatechange = null;
if (this.status === 200) {
try {
debugger
var file = request.response || request.responseText;
} catch (error) {
throw error;
}
callback(err, file);
} else {
debugger
callback(new Error("Ajax Error!!"))
}
} else {
debugger
}
}
}
//For Saving the file into zip
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
// var AllBlobs = new Blob([data], { type: "" });//application/zip //octet/stream
// var url = window.URL.createObjectURL(AllBlobs);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
//Downloaded Zip File
enter image description here

How to convert m3u8 URL to mp4 downloadable file in browser?

I am writing an extension to download videos from a website. That web site has mp4 files and m3u8 files. I have already implemented the part to download direct mp4 files. I stuck at converting the m3u8 file to mp4. I tried lot of js packages but there are a lot of dependencies and failed even after using browserfy.
Current popup.js file
function loadvideoList(callback){
chrome.storage.sync.get(['courseID'], function(result) {
if(result.courseID != 'undefined'){
$.ajax({
type: 'GET',
url: "http://localhost:80/get_videos_list/"+result.courseID,
crossDomain: true,
success: function(response) {
document.getElementById("loading_icon").style.display='none';
document.getElementById("videos_list").style.display='block';
document.getElementById("videos_list").style.padding='10px';
for(var i = 0; i < response.video_list.length; i++){
if(response.video_list[i].type == 'mp4'){
handleDownloadButton(response.video_list[i]);
}else{
// ************ HERE ***************
handleDownloadButton-m3u8Tomp4(response.video_list[i].video_url)
}
}
},
error: function (err) {
alert("unexpected error occured: "+err.code);
console.log(err);
}
});
}else{
document.getElementById("videos_list").style.display='none';
document.getElementById("videos_list").style.padding='0';
}
});
}
function handleDownloadButton(json_vid){
var node = document.createElement("DIV");
// node.style.marginBottom = "5px"
var t = document.createElement('p');
t.textContent = json_vid.file_name;
t.style.width ="240px";
node.appendChild(t);
node.style.padding = "5px";
var downloadBtn = document.createElement("BUTTON");
downloadBtn.style.cssFloat = "right";
downloadBtn.className = "btn btn-primary btn-sm download_btn";
downloadBtn.innerHTML = "Download";
// downloadBtn.value = json_vid.video_url;
node.appendChild(downloadBtn);
downloadBtn.id = json_vid.video_id;
document.getElementById("videos_list").appendChild(node);
var progress_bar = document.createElement("DIV");
progress_bar.className = "progress_container";
node.appendChild(progress_bar);
var moving_bar = document.createElement("DIV");
moving_bar.className = "progress_bar";
progress_bar.appendChild(moving_bar);
moving_bar.id = json_vid.video_id+"bar";
$(function(){
$(`#${json_vid.video_id}`).click(function(){
$(`#${json_vid.video_id}`).attr("disabled", true);
// alert(json_vid.video_url);
var that = this;
var page_url = json_vid.video_url;
var req = new XMLHttpRequest();
req.open("GET", page_url, true);
// req.withCredentials = true;
req.addEventListener("progress", function (evt) {
if(evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
// document.getElementById("download_stat").innerHTML = percentComplete;
// console.log(percentComplete);
document.getElementById(json_vid.video_id+"bar").style.width = `${percentComplete*100}%`;
document.getElementById(json_vid.video_id).textContent = `${(percentComplete*100).toFixed(2)}%`;
}
}, false);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
var filename = $(that).data('filename');
if (typeof window.chrome !== 'undefined') {
// Chrome version
$(`#${json_vid.video_id}`).attr("disabled", false);
$(`#${json_vid.video_id}`).attr("onclick", "").unbind("click");
document.getElementById(json_vid.video_id).textContent = 'Save';
$(function(){
$(`#${json_vid.video_id}`).click(function(){
// alert("download is ready");
var link = document.createElement('a');
// link.text = "download is ready";
// document.getElementById("videos_list").appendChild(link);
link.href = window.URL.createObjectURL(req.response);
link.download = json_vid.file_name;
link.click();
});
});
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
var blob = new Blob([req.response], { type: 'application/force-download' });
window.navigator.msSaveBlob(blob, filename);
} else {
// Firefox version
var file = new File([req.response], filename, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
}
};
req.send();
});
});
}
handleDownloadButton function create the button to download the direct mp4 files. I need to implement a similar function called handleDownloadButton-m3u8Tomp4(see the code sample) that should first convert the http://...file.m3u8 to a mp4 and make it also downloadable. I seek for a script in similar repos like https://github.com/puemos/hls-downloader-chrome-extension, but I was unable to do so. It would be great, If anyone could help me, Thanks in advance!
You can try to use ffmpeg.wasm to convert the .m3u8 file to a .mp4 file. ffmpeg.wasm is a pure WebAssembly / JavaScript port of FFmpeg. They even have an example repository for a Chrome extension. I haven't tested it myself though.
There are other questions here on StackOverflow that deal with how to convert a m3u8 file with FFmpeg, like this one for example.

Image Blob - Pop up window not showing content

I am working on displaying an image in blob
const file = new Blob([response.data], { type: 'image/png' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
console.log('fileURL', fileURL);
const image = document.createElement('img');
I am getting this response
PNG
IHDR2²OósRGB®ÎégAMA±üa pHYsÃÃÇo¨dã¼IDATx^ìý=ô<Ó¶Þ;Ðزg
cõ-EVÙÚÜòfã·#cV0¡\¡5È·Eüü$
]EGâ¹AD" èî÷½þûeü÷_ý×ð\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ F\¸³µ°ñ FáË¥ßçòüù«&Þv~ÑTU?ÿ^Ý}öòóÜï×'sµùÔ¤|¼þåúE8ñp
ÎÛ3Î0
¹Þuv]áÌäZ×G#¬Ïv\f.ý{ý>ã¦ñï÷õÈõÁÛÅØã·n6«ÿÞpÙ.2ßƹod
ÕEk+bv|_Hß5yÏçnØ1C´ìOÑÞøVÛ|¯
¤=ûsÔ_}BKíWÊó÷¿ç¯×ò_Þòu¸ÈÜ\dF¾a
¯FXí¸.Í\"øãñXÈ|8°àmÇýØa)#
F;L æ Øñæá_ðɾ´o»ìÔq­#ºMxVÍ_±S.|íËs¿4×â7÷="/2GýÝù¹uyZ{c6Â×·°ãÛÆyqÎ_\ÁFøÎ)¼>a}¶àº¸r)Ý
ÄÛ® ÖáÌÁÁ\à"ó'â7|ú®HNë'/Õû
D ¶³c.!lÿȶËhê¾ü"sÆß4ò#^¦¬XxcvÒ׷̽ÀEf$.í7a}¶àº4s)úáñtøÖEÛ´´ve¬í`Ê"UWäÃÛèÁ¿X}½2få¯âH²×n£Îy)U|Íg­]O½{þ«}Ï®¹JÈ-ýðkÙʯóR¸/ZLBd[NN±¨ùÖÌ¥x}³è­:#"9¯yoL÷ÿBÎj¸Õvöú_æ´v8çï.òú©Cµ-/óÊõÑ _{¹³æb[.êòRÙÖ£'lµo¦¬aò/ÌÕ1>ÿ¶ª<hPù½nüä7Ûzéú]Ïúg­ó=ó´ÞÛúºÓ¾KéåSÀÅ [¥8ìµÛ¸üí®õFxOáõÑë³×¥KËG1ýÿF&Êw\c´Û6¶Éðqò&¹mYÐÜ#ÝÄØtÓYÇÈ>Ó'´«6"áW±5k>\¥ñ[ëñîùkö[1X}Íãq{1K_1o­­Óç÷1ãÕ8t*Þå+V±]/G´v5ZI¨Úɹ¼Æ5­
µç°½Ö¿cþîÄÊLò#¬1CƳ¾zrgô·mbÄjïøÛX9N½oû½â²ÖhÏZßlë]ßo=Ku³MâáôÙ;V¼W·õN}¹­¾ýíÛH¨>4ðÆ`>çyÐ9x¾¿¢_;GC[
¯FXí¸.¾\J;Ýu¼í2ñÃccçp^iL|CJ~\vv­obú<ª
Ê··á¾Þ9k¸ðÞùöwÆ ö£ôUcgû"þÏZ5Ú7xoìq*ò¡Zå#UÛySÞkc+{gsÛw¥Me;û²ÆS×_Ò&wzßwÉýçSoçÙÂ_#2Vïÿ¶3F¬FÏoýVì÷{¾YûÇï4WÍnÀ²]û·wãÖ;ÙëÅÂ>¯´g6®qÕüìåD·ñøëYë°®^°>Ûp]þ4´õáUíøH}{cø63}ccªXòâÙØ%yCZÛx6±óÉã/ýºkyïü
ûyncÖTYü¯b`Ì)|ÜrY÷9ÁÛªßA7úÖGSÿ]sßrSôÉöëÒË
¥Ms.Ù'ÕfÏ_ï¼
´<`Äï-¯­+f#|ÈÜÑsqä·1bõÖñßddÐ7k¿óø½å¨Gíêùéy7·wܾ5¦k\#.¢ÂSx}4ÂúlÀuùÓ\ÒHãÀí\Yîæªí£§ÞÄV±AiÞóñHÜÏgyBØR:ñîù«ö¶¦r®úF޳ث¦®=+°\Ö}Î0_µ4y§o
ÝXi(ßv}ïGDrkåËË%_íò}æÿnÙ<ìoÖväÉ _ÿâÛV1â°g|1\Ìñ{ë³cmZ߬ùÎí·½ß[¶Óóìßéy_onÏe!å%ïçÏq׸Æ<´ý¾÷týu¯õFxNáõÑë³×åOsI; ["ÅhçÛÈä¸qDüL´¡o¸cçCIïÚ¶ß;Ã~sMùsßÅÿ*¿9½»#Ç;°voõâFãÛ®|<(ùÁî³ãð=Úa±mÎå'Ù¬:HùÛAËN«×C¾úrgì·ÝÀùñ;hùNi¼ßóÍÚïöûlm},ÛÕóÓóðÆ[>çö|öKnÒ²/¿]ãqù
ìPx}4ÂúlÀuùÓ\j~àv»6²î :Ã61µ
ÛÄbÞ&;v>5}ÛoxrfMc1cvµ9;õặbZÞ/ëú: ßìÛ7VªøUúÉyNtN;iîÖþbÌÍ°|ÿÿÕ
®õ·V¯G|uæÎÐo»Sãwáv8¶Ý=߬ýîßud¯}n³úwvÇ×ÛsÙ¹pîÛs«~,&ïÄ寽\ëñúhõÙëò§¹¤Æ#Ñ ßF¹7ź{h×ßàmb_IðÐ6ä+ï£æì±­yPÞ=ï¦v$ÙðlóÃ7¦Ö. ÆX°q)Ù¾×ñó­àöm/v+ñ=ó5çz[=;+ùÀg1Ù+6,Û$¿Ö
÷·­6^ùêË=e_7ê·Ý¢õ=÷Ç/kXwíÚq~/8µ÷ö3ým½ëúÞÓo9ÇûW­¿bóÜ<¯7·çµ¿æ"+Ô×®qY,qì5æ
ßȺ¸üÝ£¡-×G#¬Ïv\?Í¥øᱬuðròKþè½Yl©´¥Â¸Mlû°ø¨mtÜNSÝùlvøØ÷Îß°ãÂ×´ö=ôIµòÃ1fDɯ}³îsMséÏÓ²Kö_í7È·o¬8Ú·(öóÂß­&õÖïV¬ñ,´q­95l¯¾üþÖmJm-ZyPèæ#fG}uä'¾ítÙ=ãù8óMä·+â+íê~&Zï"¿¹4«mfC]÷Ãó8¾ÞÜÏ~ªó¼I}÷¬igÜ3>Ø?»ßÉwähxOáõÑë³×¹ôÙèóBÞ°Ô|é"£¬-|æùóÅ|Ûú.gk?aâ¹ôáärÕUù3àïÅø©/|W¼È|Ýú&gk?a}¶àº ¾ñ+û¥X¾$|ÆÁ%/2o;Sßào°AáõÑë³×¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¹pfk?aâ¢K?Ïð/á_ÿff¬á=þÑ´4?Ïsÿøz}Ä2ßç?þU{ß7?¾!׿ÏÈð´´ß;Ög;®K+ :¾¯¿Èhÿ¢ñZÈ¿Û±)ßèût9ýÿXc\dt¼>bO
.2À.2`#^°>Ûp]¾*þ½~>!zAþzþÆøóÅÇ¿ß× bó"S?K¾:sg¬ÎýcâÛà|¼)Ny>xóããóè¯÷àSà"6fk?aý«Ä'øh¾*¾úÀ_ÏÿSDlþMKåó"³x.A×ò_
±:÷OooðñVà"3¿ÞOØ­ýõ¯à£iå<TÒFÚÄÒÙÍcÿ(ë~j·|#¬¶Y»ô§¬tĨ5>ßÈ×vÄÊGî·NOÌ?À×p×ZãocXgÇjò¼û"Sæb%m®%gÔxr[æ8+¾G×?0ÂG¯º}oOYñδ+¦[ï"Ü6¿ÐµÁÉïµHÝ1#Û)~Br{,>imø÷×9Ã×qoÝbkWç*¾ÎqÏÚ­ü×÷¹6­ñ×wlîjxæîÍpKB^Px}4ÂúlÀuiåR}øäd]5lÞê&IýÃ&Ê4Mp²
V{7ïÖm|2bWósE´çÖÔK·¿>¾§ó$;ÆÒ0ÆwÛtÄ¢G¯Ñ¶6oÇÔ~Js®|Äÿ3s_·->¦g¥Möëí)ó,´ÞIÛʳ¦
When I reffer some stackoverflow answers I understood my response is wrong. my questions is how to get correct binary response ..
You can use XMLHttpRequest() or fetch() to get response as Blob
let url, w;
let request = fetch("/path/to/image");
request.then(function(response) {
return response.blob() // return `Promise` which resolves to `Blob` of response
})
.then(function(blob) {
url = URL.createObjectURL(blob);
w = window.open(url);
})
.catch(function(err) {
console.log(err)
});
let url, w;
let request = new XMLHttpRequest();
request.open("GET", "/path/to/image");
request.responseType = "blob"; // set `responseType` to `"blob"`
request.onload = function() {
url = URL.createObjectURL(blob);
w = window.open(url);
}
request.onerror = function(e) {
console.log(e);
}
request.send(null);
$http.get(ur1, {
responseType: 'blob'
}).then(function (res) {
this.download(res)
}, function (err) {
conseole.log(err)
})
}
};
this.download = function (data) {
var type = data.headers('Content-Type'),
content = data.data,
fileName = data.headers('x-ms-meta-originalname'),//Get the file name
blob = new Blob([content], {type: type}),
url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.target="_self";
a.download = fileName;
a.click();
a = undefined;
}
Additinal Details here: http://angularjstricks.blogspot.in/2017/03/download-file-from-server-with-http-in.html

submitting full HTML page to x-www-form-urlencoded as querystring encoding

I am trying to submit full HTML Page to server but I dont have a form to submit. I am not sure if i am doing it correctly but using javascript I am trying to rebuild a json object {html: htmlPage, fileName: "foo" } into a query string and then submit it to server here is the code I have. when i console str the HTML page doesnt look right. I am using jquery
var htmlPage = $("html").html();
var str = { html: htmlPage, fileName: "foo" };
var params = jQuery.param( str );
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
xhr.onerror = function(e) {
console.log('in error', e);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.send(params);
if you have jQuery, then just use ajax http://api.jquery.com/jquery.ajax/.
This will base64 encode your html, then on the server side you only have to base64 decode it, then use it. And hey the entire html code can't be counted as form-data, it's "text/html".
(updated) Try it, let me know.
// javascript
function _upload(html_string)
{
return $.ajax({
url: '/',
type: 'POST',
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: {html: btoa(html_string), fileName: "foo" },
success: function(data, textStatus, req){
console.log(textStatus);
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}

File download from google

I'm working on Google drive integration with salesforce. Currently I'm facing file corruption when I tried to download file using java script. My code is as followed
function downloadGDriveFile() {
var id = '0B3EI0BFOUwSydHZNZXdIZ3lDZzg';
var downloadUrl = 'https://www.googleapis.com/drive/v2/files/'+ id+'?alt=media';
var accessToken = MY ACCESS TOKEN;
var mType = 'image/jpeg';
var name = 'Internet_of_Things.jpg';
if (downloadUrl) {
var xhr = new XMLHttpRequest();
xhr.open('GET', downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
onDownload(xhr.response);
};
xhr.onerror = function() {
//downloadFile(null);
};
xhr.send();
}
else {
alert("Unable to download file.");
}
}
function onDownload(data) {
var filename = 'Internet_of_Things.jpg';
var blob = new Blob([data], { type: "image/jpeg" });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
//window.location = downloadUrl;
}
alert(11);
//URL.revokeObjectURL(downloadUrl);
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 1); // cleanup
}
}
when file is downloaded file is corrupted.File content shown as follow
���� JFIF �� hExif MM * > F( 1 N Paint.NET v3.5.11 �� C �� C�� ��" ��
Dose any one can help me to sort this out. Do I need to encode or decode the Response from Google REST API?

Categories