Here is my script for Downloading an image working perfectly on Computer, But It's not working in Mobile Browsers,Nothing takes place when clicking the Button
Function
<script>
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
</script>
The HTML Script
<button onclick=forceDownload("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png","Test") type="button">Download</button></a>
Related
I would like to load a file from my storage (Azure) where i don't know the file extension from but i do know the filename, after i would like to use the right file for the src.video. Basically feed every optional video source into videoJS.
this works, but only for two predefined files (mp4/mov):
var video = document.getElementById('my-player')
fileExists()
function fileExists() {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://linktovideo + '.mp4', true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
console.log(xhr.status)
if (xhr.status == 200) {
console.log("MP4 video)
video.src = 'https://linktovideo' + '.mp4';
} else {
console.log("MOV video")
video.src = 'https://linktovideo' + '.mov';
}
}
}
what i like to do is something as this, make a general search for the file (.*);
var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://linktovideo + '.*', true);
xhr.send();
xhr.onreadystatechange = processRequest;
then from the actual file extract the extension and glue that to
video.src = 'https://linktovideo' + '.webm';
would something like this be possible? Now of course the XMLrequest returns 404
any ideas or suggestions?
Firebase's documentation covers downloading an image if you call storage and getDownloadURL, and I have this working fine (straight from the docs):
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
// Or inserted into an <img> element:
var img = document.getElementById('myimg');
img.src = url;
}).catch(function(error) {
// Handle any errors
});
However, I already have a URL and want to download an image without calling firebase storage. This is my attempt:
var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
console.log(url);
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
But, no file is downloaded and no error is shown in the browser's development tools.
Note: I do know the URL is correct because if I put URL directly into my browser search bar, I am able to access the file and download it.
Does anyone know how to download an image using a Download URL that you already have (without calling Firebase Storage as they do in the docs)?
This ended up working for me:
var url = "https://firebasestorage.googleapis.com/v0/b/somerandombucketname..."
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = "fileDownloaded.filetype"; // Name the file anything you'd like.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
xhr.open('GET', url);
xhr.send();
This is essentially creating an a href to the URL I have and then clicking the a href programmatically when the xhr response is received.
It is not clear to me why the first way doesn't work as well, but hopefully this helps others that face the same issue.
Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},
I have used below code to download image with given name. But this seems does not download image with it's own image extension.
Here is HTML
<a id="btnDownload" href="www.mywebsite.com/images/myimage.jpg" onClick="downloadImage(www.mywebsite.com/images/myimage.jpg);" >download</a>
and code
function downloadImage(sUrl){
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', sUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
var res = xhr.response;
var blob = new Blob([res], {type:'image'});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "My image name";
document.body.appendChild(a);
a.click();
};
xhr.send();
}
What i want is i want downloaded image with "My image name"."extension". Here image does have alternative extension like jpeg, png, gif.
But this code always download file without extension. Any changes here?
To get the extension in your example you could do:
a.download = "My image Name." + window.URL.split('.').pop();
Yet I would work with different data-attributes:
<html>
<!--
You can put the href and the name you want to see in different data attributes.
Also one can add IE support.
-->
<head>
<script>
//e:=<a [data-name] [data-href]>
function downloadMe(e){
var tF = e.getAttribute('data-name');
var tURL = e.getAttribute('data-href')
var tR = new XMLHttpRequest();
tR.open('GET', tURL, true);
tR.responseType = 'blob';
tR.onload = function(e){
var tB = this.response;
if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}
};
tR.send();
return false
}
</script>
</head>
<body>
<a href = '#' data-href = 'A.png' data-name = 'My Name.png' onclick = 'return downloadMe(this)'>download</a>
</body>
</html>
Hi i want to save a audio file path into database and audio file into my upload folder here is my code:-
<a class="btn btn-large btn-danger" id="ahref" target="_blank" onclick="$('#audioLayerControl')[0].save($('#ahref')[0]);"><i class="icon-fire"></i> save</a>
When i clicked on this link my audio which is recorded by me is saved in downloads folder and i can play it but i want to save it in my uploads folder i am getting blob url like this blob:http%3A//localhost%3A8383/0dd9e04b-d6db-4c8c-94b5-51cfb619f725 here is its script :-
this.save = function save(saveLink)
{
var url = this.toWave().toBlobUrlAsync("application/octet-stream");
document.getElementById("ahref").src=url;
var final=document.getElementById("ahref").download = new Date().toISOString() + '.wav';
};
Thank you please help me.
Updated After using Ajax
var blobUrl=url;
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
//xhr.open('GET', blobUrl);
xhr.open('POST', 'upload.php', true);
xhr.send(blobUrl);
Upload.php
<?php
error_reporting(0);
if( isset($HTTP_RAW_POST_DATA))
{
echo $cad = $HTTP_RAW_POST_DATA;
}
?>
Ouput:-blob:http%3A//localhost%3A8383/5155c610-dec6-4e60-8ef7-e14a56aa73d2
and in the browser url is data:text/html;base64,YmxvYjpodHRwJTNBLy9sb2NhbGhvc3QlM0E4MzgzLzUxNTVjNjEwLWRlYzYtNGU2MC04ZWY3LWUxNGE1NmFhNzNkMg==
i'll add :
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
just before the :
xhr.open('POST', 'upload.php', true);