JavaScript to download textfiles instead of opening - javascript

I am trying to create virtual links of list of files to be downloaded using javascript. The problem is that it is opening all files in the new tabs instead of downloading directly. I want it to be downloaded rather than open in a new tab.
Any help regarding it will be highly appreciated. So far, I have tried the following code to serve the purpose.
var link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < links.length; i++) {
link.href = links[i];
link.download = tfiles[i];
link.target = '_blank';
link.click();
}
document.body.removeChild(link);

Instead of setting the download attribute like this link.download = tfiles[i]; use setAttribute('download',"download_filename"). So the resulting code will look like
var link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < links.length; i++) {
link.href = links[i];
link.setAttribute('download',tfiles[i]);
link.target = '_blank';
link.click();
}
document.body.removeChild(link);
Assuming that tfiles is an array of the file names of files that you want to download.
Try out this working code in a simple html file for more exercise. The code might not work in stackoverflow run snippet, since this is a sand-boxed env.
<!DOCTYPE html>
<html>
<body>
<script>
function download() {
var link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
link.setAttribute('download', "download");
link.href = "https://picsum.photos/id/237/200/300";
link.target = '_blank';
link.click();
}
</script>
<p>Click on the download button to download the image:
<p>
<button onClick="download()"> download</button>
<p><b>Note:</b> The download attribute is not supported in Edge version 12, IE, Safari 10 (and earlier), or Opera version 12 (and earlier).</p>
</body>
</html>

You will want to use a Blob for this. You can use fetch to get the blob and then download. Similar to below:
var link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < links.length; i++)
{
fetch(links[i])
.then(response => response.blob())
.then(blob => {
var url = window.URL.createObjectURL(blob);
link.href = url;
link.download = 'file_' + i;
link.click();
window.URL.revokeObjectURL(url)
})
}
document.body.removeChild(link);

Related

cannot download file from BlobUrl (using MediaReader)

I have the following code:
let self = this;
this.chunks = [];
const canvas2 = document.getElementById("self-canvas");
let recordStream = canvas2.captureStream(1);
var options;
options = {mimeType: 'video/webm; codecs=vp9'};
this.recorder = new MediaRecorder(recordStream, options);
this.recorder.ondataavailable = function(evt) {
self.chunks.push(evt.data);
};
this.recorder.onstop = function(evt) {
console.log("recorder stopping");
const link = document.createElement('a');
const videoBlob = new Blob(self.chunks, { type: "video/webm" });
console.log("file size: " + videoBlob.size);
const url = URL.createObjectURL(videoBlob);
link.href = url;
link.download = "sample.webm";
document.body.append(link);
link.click(); //if I comment out here I can see the video
};
console.log("finished setting controller")
console.log("recorder starting");
this.recorder.start(10000);
// the recorder.stop is called somewhere else
What it is supposed to do is pretty simple:
I have the element with id "self-canvas" that is showing my camera.
Now I am trying to record the camera and download the video from the browser using MediaRecorder, but for some reason I am unable to download the file.
I am sure that the file is being recorded, and console.log("file size: " + videoBlob.size); does not return empty.
But when I let the code run, instead of downloading the file, it tries to open it on the same window, and I cannot even see the video because the previous window disappears with the data of the recording.
However if I comment out the link.click(); I am able to see the video by opening the link on a new page (without closing the previous one). But it still doesn't download...
I used this as example, what am I doing wrong?
For heaven's sake...
I just added target blank and it worked.
link.href = url;
link.download = "sample.webm";
link.target = '_blank';
Probably because the resources are lost if it tries to open on the same page, and because it doesn't actually download the file if it is not a link "click".
Still, I never saw anyone having to add target blank in their examples like this one.
So I wonder why this is the case only for me...

How do I make a button that will download a file

I'm attempting to make a button that will download an image file upon pressing, but what I've made will only take me to the file itself.
Html:
<button onclick="file()">Click me, i'll download an image</button>
Javascript:
function file() {
const anchor = document.createElement("a");
anchor.href = "dingus.png";
anchor.download = "dingus.png";
document.body.appendChild(anchor);
anchor.click();
}
Here it is, don't forget to remove the appended element.
function download(url) {
const anchor = document.createElement('a')
anchor.href = url
anchor.download = url.split('/').pop()
document.body.appendChild(anchor)
anchor.click()
document.body.removeChild(anchor)
}
download path should be in HTTP path then only it will work. local that will not work
Example
function file() {
const anchor = document.createElement("a");
anchor.href = "http://www.exampleApiPath.com/dingus.png";
anchor.download = "http://www.exampleApiPath.com/dingus.png";
document.body.appendChild(anchor);
anchor.click(); }

Internet Explorer - The data area passed to a system call is too small - Downloading png with the uri

I am trying to download a png file using the uri (code below). It works in Chrome, Firefox and Safari - but not (of course) in Internet Explorer. I am on Windows 7, so I am using IE11 in Edge Document Mode. The error is "The data area passed to a system call is too small." I've read in this MDN post
IE9 and later, as well as Edge, supports data URIs in CSS and JS
files, but not in HTML files, with a max size of 4GB.
My URI is only 1410 bytes (using uri.length). Any ideas why I am getting the error with data of this size and how to fix it?
The download function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
The uri format:
"data:image/png;base64,iVBORw0KGgo ETC..."
The solution is below. I can't seem to find the link to give credit, but this solved it. Instead of converting the canvas to a uri first, I pass the canvas and either convert to a uri and download using a link or (for IE) I convert to a blob and use canavas.msToBlob() and msSaveBlob()
function downloadURI(canvas, name) {
if (navigator.msSaveBlob) { // IE10+
var blob = canvas.msToBlob();
return navigator.msSaveBlob(blob, name);
} else {
var uri = canvas.toDataURL("image/png")
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
if (link.click) {
link.click();
} else {
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window);
link.dispatchEvent(event);
}
document.body.removeChild(link);
}
}

file is not downloading blob link

I have below snippet that download the "Test.csv" in IE11, CHROME very well.
But nothing happens in case of FIREFOX 39.0
Any Help will be appreciated.
var blob = new Blob([], { type: 'text/csv' });
/* It will work for IE versions
window.navigator.msSaveBlob(blob, 'Test.csv');
*/
var link = document.createElement("a");
//link.setAttribute("onclick","alert('Click Fired')");
link.href = URL.createObjectURL(blob);
link.download = 'Test.csv';
link.click();
Fiddle: http://jsfiddle.net/rq8460cL/2/
I seems like you have to add the link to the dom before you click it
var blob = new Blob([], { type: 'text/csv' });
/* It will work for IE versions
window.navigator.msSaveBlob(blob, 'Test.csv');
*/
var link = document.createElement("a");
//link.setAttribute("onclick","alert('Click Fired')");
link.href = URL.createObjectURL(blob);
link.download = 'Test.csv';
document.body.appendChild(link);
link.click();
http://jsfiddle.net/rq8460cL/3/

jQuery Save Image Onclick

On my website I have a jQuery script that, if the download button is clicked it will open the image that you want in new window.
My question is, how can I make this script when you click the button the image will save automatically and not open in a new window.
My code :
<script type="text/javascript">
$(document).ready(function (){
$('#download-btn').click(function(){
var size = $('#size').val();
window.open(size);
});
})
</script>
First I try jqueryfiledonwloader but not work on image file,after a some searching I found below solution,This work for me charmly,try this
<script type="text/javascript">
$(document).ready(function (){
$('#download-btn').click(function(){
var link = document.createElement('a');
link.href = '/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'; // use realtive url
link.download = 'MyToy.jpeg';
document.body.appendChild(link);
link.click();
});
})
</script>
<button class="btn btn-success" style="width: 250px;" data-image="/media/result/online_resultjpg_Page68.jpg" data-exam="GMO" data-roll="110211" onclick="downloadCertificate(this);" >Download Certificate</button>
<script type="text/javascript">
function downloadCertificate(obj){
var link = document.createElement('a');
const image = $(obj).data("image");
const img_ext = image.split(".");
const ext = img_ext[img_ext.length - 1];
link.href = image;
link.download = $(obj).data("exam") + "_" + $(obj).data("roll") + ext;
document.body.appendChild(link);
link.click();
}
</script>
Yuseferi script solution could be transformed into a simple anchor tag we put before the closing of the #download-btn one:
<a href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
download='MyToy.jpeg'>MyToy.jpeg</a>
By the way, download is a standard HTML5 anchor tag (MDN) attribute and, in script, it is flagged "experimental": maybe because of unwanted side effect. Still Yuseferi solution should be full proof.

Categories