image does not download with it's own extension - javascript

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>

Related

Downloading Image not Working in Mobile Browser

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>

i couldn't get the download URL for the image

Get The download url and assign it to a variable
<html>
<head>
<h1>retrieve data</h1>
<h2 id=myimg></h2>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
//firebase initialization
};
firebase.initializeApp(config);
</script>
<script>
storageRef.child('1.jpg').getDownloadURL().then(function (url) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function (event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
var img = document.getElementById('myimg');
img.src = url;
}).catch(function (error) {
});
</script>
</body>
</html>
i want the download url to be assigned
i want to retrieve the download URL from the firestorage and assign it to a variable
what modification should i do in this code to get the download URL of the uploaded image
Include the folder you're getting the image from 'pics/1.jpg' then remove the first section of your code that downloads the image and leave the bottom part that only assigns the URL to the image.
var storageRef = firebase.storage().ref();
storageRef.child('pics/1.jpg').getDownloadURL().then(function (url) {
var img = document.getElementById('myimg');
img.src = url;
}).catch(function (error) {
});

Download PDF file with AJAX and HTML button (no jquery)

I want to download a PDF file when I press an HTML button. I want the click event to be in a JS file.
I need something that do the same thig as the code below but in a JS file :
<a href="url" download>
<button>Download</button>
</a>
I tried to follow this but it doesn't create my button:
var req = new XMLHttpRequest();
req.open("GET", "url", true);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
// test for IE
if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PdfName-" + new Date().getTime() + ".pdf";
// append the link to the document body
document.body.appendChild(link);
link.click();
}
}
};
req.send();
If you already have the URL, and you just want the file to be downloaded, use an invisible link, and click it for the user:
function triggerDownload(url, filename) {
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = `none`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Note the adding to the document, which is required for the link to count as a real link.
Just made it work, here is my working code
const blob = new Blob([response], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "filename.pdf";
link.click();
I would agree with mike, you don't need any ajax to download it
if you want to add the timestamp for when you downloaded it, just change the download attribute dynamical
Download
or better yet add it in the backend using content-disposition attachment header

Firebase Download Image using Download URL (Without Calling Storage)

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.

How to download file using JavaScript only

I have an only JavaScript page and .asmx page. I want to download file
using only JavaScript how can I download the file. I want to download a particular resume.
I am getting resume here,
var res = data[i].resume;
You may use different third-party libraries:
jQuery.fileDownload
It takes URL as an input and downloads a file while shows a loading dialog.
Github: https://github.com/johnculviner/jquery.fileDownload
Demo: http://jqueryfiledownload.apphb.com/
Usage:
$.fileDownload(requestUrl, {
preparingMessageHtml: "Downloading...",
failMessageHtml: "Error, please try again."
});
FileSaver.js
It takes Blob object as an input and downloads it. Blob can be acquired using XMLHttpRequest.
Github: https://github.com/eligrey/FileSaver.js/
Demo: http://eligrey.com/demos/FileSaver.js/
Usage:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveAs(this.response, 'filename.txt'); // saveAs is a part of FileSaver.js
};
xhr.send();
It may also be used to save canvas-based images, dynamically generated text and any other Blobs.
Or write it yourself
function saveData(blob, fileName) // does the same as FileSaver.js
{
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
Now, if it is a text file, you can simply download it, create a blob, and save it:
$.ajax({
url: requestUrl,
processData: false,
dataType: 'text'
}).done(function(data) {
var blob = new Blob([data], { type: "text/plain; encoding=utf8" });
saveData(blob, 'filename.txt');
});
Or you can use XMLHttpRequest which works great for any types of files, including binary:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveData(this.response, 'filename'); // saveAs is now your function
};
xhr.send();
Here is the working demo. Note that this fiddle downloads a file right after opening it. The file is just a random source file from GitHub.
Actually, There is a javascript library called FileSaver.js, FileSaver.js saving file on the client-side. it can help you achieve this.
here: https://github.com/eligrey/FileSaver.js
Usage:
<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
<script>
function SaveAsFile(t,f,m) {
try {
var b = new Blob([t],{type:m});
saveAs(b, f);
} catch (e) {
window.open("data:"+m+"," + encodeURIComponent(t), '_blank','');
}
}
SaveAsFile("text","filename.txt","text/plain;charset=utf-8");
</script>
If you use jQuery you can do some like that:
var getFile = function( path_to_file, callback ) {
$.ajax( {
url: path_to_file,
success: callback
} );
};
getFile( 'path_to_your_asmx_page', function( file_as_text ) {
console.log( file_as_text );
} );
Call getFile and you'll get file content in callback function
Use the code below.
var sampleBytes = base64ToArrayBuffer('THISISTHETESTDATA');
saveByteArray([sampleBytes], 'ashok.text');
function base64ToArrayBuffer(base64)
{
var binaryString = window.atob(base64);
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;
}
var saveByteArray = (function ()
{
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());

Categories

Resources