i couldn't get the download URL for the image - javascript

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

Related

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.

image does not download with it's own extension

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>

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

Convert local image to base64 string in Javascript

I'm trying to convert a local image to Base64 string. I am not using any HTML and simply need javascript which references the image's path within the code.
For instance, converting:
C:\Users\Work\Desktop\TestImage.jpg
into
/9j/4AAQSkZJRgABAQEASABIAAD/4QBKRXhpZgAASUkqAAgAAAADABoBBQABAAAAMgAAABsBBQABAAAAOgAAACgBAwABAAAAAgAAAAAAAAAAVOoqgJaYAABU6iqAlpgA/+IMWElDQ19QUk9GSUxFAAEBAAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIH.....etc...
There are many posts like this but they all seem to utilize HTML in some way, in order to identify the file path. I'm hoping I can write a defined filepath within the javascript.
I tried this to no avail:
function convertImgToBase64()
{
var canvas = document.createElement('CANVAS');
img = document.createElement('img'),
img.src = C:\Users\Work\Desktop\TestImage.jpg;
img.onload = function()
{
canvas.height = img.height;
canvas.width = img.width;
var dataURL = canvas.toDataURL('image/png');
alert(dataURL);
canvas = null;
};
}
One example has the following html and javascript, but I'm hoping this can be consolidated together. Thanks for your support
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type='file' id="asd" />
<br>
<img id="img" src="//placehold.it/1x1/" />
<div id="base"></div>
</body>
</html>
Javascript:
function el(id){return document.getElementById(id);} // Get elem by ID
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
el("img").src = e.target.result;
el("base").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("asd").addEventListener("change", readImage, false);\
Its demo found here
Try utilizing XMLHttpRequest() set responseType to Blob , use FileReader() at XMLHttpRequest onload event to read response as data URI
var xhr = new XMLHttpRequest();
xhr.open("GET", "/path/to/local/image/file", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res)
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()

Read xml file, modify the values/add elements/attributes and save the xml how?

Using javascript, I want to read xml file from the disk, modify the values/add elements/attributes and save the xml back to disk.
Anyone knows here can i find examples that works with IE and Firefox? I allready find examples to read, now changing values that's the problem.
Thanks
Assuming you are trying to read and write to disk from the browser and not node.js,
the first step is to use an input tag of type file to get access to the file system.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>
As soon as a file is selected we want to extract the blob from the element.
A good moment to do that is during the change event.
const input = document.querySelector('#input');
input.addEventListener('change', () => {
const file = input.files.item(0);
});
There is more than one way to parse the blob into a tree of elements.
Here I took advantage of the fact that the browser parses xml documents in HTTP requests.
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load', () => {
callback(request.response);
});
request.send();
}
After the blob has been parsed we can manipulate it like we would manipulate the DOM tree.
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
In order to save the file to disk we need to reverse the process of parsing,
converting the tree of elements back to a string.
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
The only thing left is to send the file back to disk.
To achieve this we can trigger a click event on a link with our modified file.
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
Here is the complete code
const input = document.querySelector('#input');
input.addEventListener('change', () => {
const file = input.files.item(0);
blobToDocument(file, (xmlDocument) => {
editDocument(xmlDocument);
download(documentToString(xmlDocument), "text/xml");
});
});
function blobToDocument(blob, callback) {
const url = URL.createObjectURL(blob);
const request = new XMLHttpRequest();
request.open('Get', url);
request.responseType = 'document';
request.addEventListener('load', () => {
callback(request.response);
});
request.send();
}
function editDocument(document) {
const element = document.createElement('editor');
element.textContent = 'JavaScript';
document.firstChild.appendChild(element);
return document;
}
function documentToString(document) {
const serializer = new XMLSerializer();
return serializer.serializeToString(document);
}
function download(string, mime) {
const blob = new Blob([string], { type: mime });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = 'document.xml';
a.click();
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="file" id="input" accept="text/xml">
<script src="script.js"></script>
</body>

Categories

Resources