I have this event handler that does downloading and that's working great on all browsers except IE, so I handled it with msSaveBlob and it download file, but when I open it, it said format isn't good, so my guess is that I don't use valid data in blob.
$(document).on('click', '.register-file-uploader-download-file', function () {
let $fileResultsItem = $(this).closest('.form-fields__file-results-item');
const fileName = $fileResultsItem.find('.multiple-files-upload-item').data('filename');
const fileUrl = $fileResultsItem.find('.multiple-files-upload-item').val();
if (fileUrl.length > 0) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var url = window.URL || window.webkitURL;
let blobFileUrl = url.createObjectURL(this.response);
if (window.navigator && navigator.msSaveBlob) { // For IE
const blobObj = new Blob([this.response], { type: 'application/octet-stream' });
return navigator.msSaveBlob(blobObj, fileName);
}
const a = document.createElement('a');
a.style.display = 'none';
a.href = blobFileUrl;
a.download = `${fileName}`;
document.body.appendChild(a);
a.click();
url.revokeObjectURL(blobFileUrl);
}
};
xhr.open('GET', fileUrl);
xhr.responseType = 'blob';
xhr.send();
}
});
I found error. Code is working fine, problem is in fact that I tried to download image that was uploaded on stage server, and when I uploaded and downloaded it and it's working
Related
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
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.
enter image description hereWe have a service that interacts with box.com and returns a file in binary format.
I am trying to hit that service from java-script to get binary file and render/dowload as actual file using below code but no response is being received (I have verified that service is returning the response).
Console logs are blank.
Any help is greatly appreciated.
<h1>File Download</h1>
<button type="button" onclick="loadDoc()">Download</button>
<p id="demo"></p>
function loadDoc() {
var xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Basic xxcxcsdfdfdferererer=");
//xhr.setRequestHeader("Access-Control-Allow-Origin", true);
xhr.responseType = 'arraybuffer';
xhr.send(JSON.stringify({projects: [{id: "xxxxxx", fileId: "1234456566"}]}));
xhr.onreadystatechange = function () {
if (this.readyState == 4 && 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 = typeof File === 'function' ? new File([this.response], filename, { type: type }) : new Blob([this.response], { type: type });
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;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
}
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?
I'm trying to get a MediaStream object into a blob, but I have some problems.
This is the part of my script for the UserMedia component:
var mediastream = undefined;
var blob = undefined;
var video = document.getElementById('test');
This is my script where I'm trying my test:
var mediastream = undefined;
var blobUrl = undefined;
var video = document.getElementById('test');
function successCallback (stream) {
mediastream = stream;
blobUrl = URL.createObjectURL(mediastream);
var xhr = new XMLHttpRequest();
xhr.open('GET', blobUrl, true);
xhr.responseType = 'arraybuffer';
xhr.withCredentials = true;
xhr.onreadystatechange = function () {
console.log('xhr.readyState='+xhr.readyState);
if (xhr.readyState !== 4) {
return;
} else {
var myBlob = this.response;
}
function errorCallback (stream) {
console.log('error');
}
Setting the blobUrl to the video.src I don't have any problem:
video.src = blobUrl; <- WORKS
But if I call the urlBob url (like this one: blob:http%3A//localhost%3A8080/b1ffa5b7-c0cc-4acf-8890-f5d0f08de9cb ) I obtain HTTP status 404.
For sure there is something wrong on my implementation.
Any suggestions?
Thank you!