Download a file from a link on button value - javascript

I searched a lot but couldn't find a solution I thank anyone who can help me.
I want to download files on button click but based on values in the text of buttons.
I have three buttons in my HTML like this
<input type="button" onclick="myFunction(this, name1.mp3)" value="button1.mp3">
<input type="button" onclick="myFunction(this, name2.mp3)" value="button2.mp3">
<input type="button" onclick="myFunction(this, name3.mp3)" value="button3.mp3">
my JavaScript is
function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
var downloadFileWithThisName = name;
---my download code---
}
How can I download my url with the name I passed to function?
what should I write for ---my download code--- part?
Thank you in advance.

function myFunction(elmnt, name) {
var url = "http://mysite*com/" + elmnt.value;
const a = document.createElement('a');
a.href = url;
a.download = name; // here you can specify your filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}

What you could do is to dynamically create an A element, add the 'download' attribute, set the Href and click it, all in code. Then remove it from the DOM.
The best answer judging for your code is shown here: https://stackoverflow.com/a/42696866/1891140
var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
But you also can do it by using a simple JQUERY:
$("<a href='"+url+"' download class='hidden-a'></a>").appendTo("body");
$(".hidden-a")[0].click();

Related

Download an image from an html input

I've a problem with my website. I want when an user add an image from
this input :
`input type="file" class="form-control-file" id="Image" name="Image">`
I want to automatically download this image. I would prefer to download from front end. I try in JavaScript but not working.... Does anyone have an idea please ?
I despair.
Anatole
Edit : I want to download the image in my website folder ^^
you can add onchange listener that track input change
user input
<input oninput="onclickhandler(this)"></input>
script
<script>
function download(filename, url) {
var element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
//remove the hidden link
//document.body.removeChild(element);
}
function onclickhandler(e) {
var name = e.files[0].name;
var file = e.files[0];
var blob = new Blob([file]);
var url = URL.createObjectURL(blob);
download(name,url);
}
</script>

Calling href from onclick method does not work

Hello i was wondering how can i invoke an a click from a button onclick event:
I have made it work so far with these 2 methods :
<a class="button" type="application/octet-stream" href="http://localhost:5300/File" download>Click here for dld</a>
<input type="button" onclick="location.href='http://localhost:5300/File';" value="Download"/>
But i can not make it work with js ; i have tried like this:
<button onclick="Save('http://localhost:5300/File')">Download</button>
function Save(url){
var link=document.createElement('a');
link.url=url;
link.name="Download";
link.type="application/octet-stream";
document.body.append(link);
link.click();
document.body.removeChild(link);
delete link;
}
P.S I need to use the <button></button> and not the input !
Your code creates a link, clicks it then deletes it. You can instead just run window.location.href as you did in the HTML example.
onclick = "Save('http://localhost:5300/File')" > Download < /button>
function Save(url) {
window.location.href = url;
}
<button onclick="Save('http://localhost:5300/File')">Download</button>
Or, if you stick to your method of creating a link, you should set href for the link, not url.
function Save(url) {
var link = document.createElement('a');
link.href = url;
link.name = "Download";
link.type = "application/octet-stream";
document.body.append(link);
link.click();
document.body.removeChild(link);
}
<button onclick="Save('http://localhost:5300/File')">Download</button>
Add button type='button'
function Save(url) {
console.log(url)
var link = document.createElement('a');
link.url = url;
link.name = "Download";
link.type = "application/octet-stream";
document.body.append(link);
link.click();
document.body.removeChild(link);
delete link;
}
<a class="button" type="application/octet-stream" href="http://localhost:5300/File" download>Click here for dld</a>
<button type='button' onclick="Save('http://localhost:5300/File')">Download</button>
Do you actually need to create an a element? If not, I would use window.location.href, which is similar to clicking on a link.
Example:
function Save(url){
window.location.href = url;
}
The only issue with this might be if you're linking to an HTTP (non-secure) site from an HTTPS (secure) site.
const btn = document.querySelector('button');
btn.addEventListener('click', function(e) {
e.preventDefault();
save('http://localhost:5300/File');
});
function save(url) {
let link = document.createElement('a');
link.href = url;
link.name = "Download";
link.type = "application/octet-stream";
document.body.append(link);
link.click();
document.body.removeChild(link);
delete link;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Download</button>

Export AngularJS table to .CSV directing to about:blank page?

I currently have a Javascript function which exports my AngularJS table of JSON data to a .csv file by div ID as shown:
$scope.exportToExcel = function (tableId) { // ex: '#my-table'
var exportHref = Excel.tableToExcel(tableId, 'WireWorkbenchDataExport');
$timeout(function () { location.href = exportHref; }, 100); // trigger download
}
Which I call like so
<button style="float: right;" class="btn btn-link" ng-click="exportToExcel('#codeProjectsTable')" filename="test.csv">
<span class="glyphicon glyphicon-share"></span>
Export table
</button>
This works well for data sets with ~400 records or less (20 columns per record), but I'm trying to export nearly 1,000 records for further reporting and I am simply being directed to an about:blank page.
I'm suspecting that it is either
Unable to export this large of a file
Timing out because of a long request
Thanks in advance.
I used following logic for to export
var fileName = 'users_export_' + moment().format('YYYY-MM-DD') + '.csv';
var url = URL.createObjectURL(new Blob([response.data]));
var a = document.createElement('a');
a.href = url;
a.download = fileName;
a.target = '_blank';
a.click();
And its working for large for large file/data

Downloading file made with jquery's .innerhtml breaks at the first "#"

I have this code:
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //displays fine
a.href = "data:image/svg+xml," + dd.innerHTML;
a.click();//downloaded file cuts off at the first "#"
}
When the alert displays it it's okay, the downloaded version is cut off before the first "#". How do I fix this?
Since this is part of a href, you need to url-encode your data first, eg.
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //should still display fine
a.href = "data:image/svg+xml," + encodeURIComponent(dd.innerHTML);
a.click();//should now not cut off.
}
The safe variation of # in a url is %23%0A (check out this tool: http://meyerweb.com/eric/tools/dencoder/).

How to save a base64 image to user's disk using JavaScript?

I have converted the source content from the <img> html tag to a base64String using JavaScript. The image was displayed clearly. Now I want to save that image to user's disk using javascript.
<html>
<head>
<script>
function saveImageAs () {
var imgOrURL;
embedImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA" +
"AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO" +
"9TXL0Y4OHwAAAABJRU5ErkJggg==";
imgOrURL = embedImage;
if (typeof imgOrURL == 'object')
imgOrURL = embedImage.src;
window.win = open(imgOrURL);
setTimeout('win.document.execCommand("SaveAs")', 0);
}
</script>
</head>
<body>
<a href="#" ONCLICK="saveImageAs(); return false" >save image</a>
<img id="embedImage" alt="Red dot">
</body>
</html>
This code worked well when I set the image path as source for <img> html tag. However, when I pass the source as base64String does not work.
How to achieve what I want?
HTML5 download attribute
Just to allow user to download the image or other file you may use the HTML5 download attribute.
Static file download
<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Dynamic file download
In cases requesting image dynamically it is possible to emulate such download.
If your image is already loaded and you have the base64 source then:
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
}
Otherwise if image file is downloaded as Blob you can use FileReader to convert it to Base64:
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function () {
var base64 = reader.result ;
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
};
reader.readAsDataURL(blob);
}
Firefox
The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).
IE is not supported: Caniuse link
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
atob()
btoa()
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {
const img = document.getElementById('embedImage');
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +
'9TXL0Y4OHwAAAABJRU5ErkJggg==';
img.addEventListener('load', () => button.removeAttribute('disabled'));
const button = document.getElementById('saveImage');
button.addEventListener('click', () => {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
});
});
<!DOCTYPE html>
<html>
<body>
<img id="embedImage" alt="Red dot" />
<button id="saveImage" disabled="disabled">save image</button>
</body>
</html>
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
Check out https://github.com/eligrey/FileSaver.js/ which wraps the HTML5 method and provides workarounds for e.g. IE10.

Categories