Download text file or image throw javascript on Firefox - javascript

I'm trying to download a file using a http link.
This is the code:
downloadFile: function (fileName, url) {
var link = document.createElement('a');
link.setAttribute('download', fileName);
link.setAttribute('type', 'application/octet-stream');
link.target = '_blank';
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
This works on Chrome and Edge but not on Firefox.
When I tried to download a text file or image, the browser opens a new tab this the file content rendered. I need that the browser open the default download window.
Is it possible?
This is an example of URL that I use: http://localhost:17671/docstmp/528d149e37467a53faeeeb0556901d87/ToDo.txt
I created this jsfiddle to demonstrate: jsfiddle.net/hp7yod85

The requested resource does not have Access-Control-Allow-Origin header set, and has X-Frame-Options header set to SAMEORIGIN to prevent loading into <iframe> element.
You can use YQL to retrieve content, then create a data URL of text content at returned results, then create an <a> element with href set to data URL. Returns expected result of opening dialog which prompts to open file within text editor or save file at firefox 47.
<!DOCTYPE html>
<html>
<body>
<button onclick="downloadFile()">Test</button>
<script>
function downloadFile() {
var request = new XMLHttpRequest();
var url = 'https://query.yahooapis.com/v1/public/yql?q='
+ 'select * from html where '
+ 'url="http://www.ietf.org/rfc/bcp/bcp47.txt"&format=json&callback='
request.open("GET", url);
request.onload = function() {
var data = JSON.parse(this.responseText).query.results.body.content;
var a = document.createElement("a");
a.href = "data:text/plain," + data;
a.download = "bcp47.txt";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
request.send()
}
</script>
</body>
</html>
plnkr http://plnkr.co/edit/8JBBhVwIy0Icr2MaQZif?p=preview

Related

Download File through JavaScript

I have created a function to download the file, but the issue is it opens the file on the same tab, I a trying to force download this file in the system.
I read other threads but didn't get the answer as I was expected and helpful.
Please help me create this function that downloads the file.
I have tried this code as below
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.click();
link.remove();
}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
Seems like - as with normal links - you need to set the target attribute.
Note: snippet won't work here because popups are blocked. This means that it does work.
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.setAttribute("target", "_blank");
link.click();
link.remove();
}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
here is a typical js download function sample. In your code, firstly you should replace 'name' with name, using the variable given.
function loadPdfFile(uri, pFileName) {
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = pFileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
The reason why it only opens the PDF might be you are running your code locally, you could try to put it to your server and test.
If you want to open the file in a new tab, you can simply add a target="_blank" attribute (link.setAttribute("target", "_blank");).
If you want to forcefully download the file instead of opening/previewing it in the browser, you can convert the file URI to a blob. For example:
async function downloadURI(uri, name) {
const link = document.createElement("a");
link.download = name;
const data = await fetch(uri).then((res) => res.blob())
link.href = window.URL.createObjectURL(
new Blob([data], { type: 'application/pdf' })
);
link.click();
link.remove();
window.URL.revokeObjectURL(link.href);
}
JS Fiddle: https://jsfiddle.net/sh4dfm6a/
if you need to open it in new tab just add target attribute like below EX
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.target = "_blank";
link.click();
link.remove();}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');

Javascript display filename instead of blob name in the PDF URL

I am able to get the pdf in the new window with URL as
htts://mydomainname/410-8d9c-4883-86c5-d76c50a24a1d
I want to remove the auto generated blob name (410-8d9c-4883-86c5-d76c50a24a1d) in the generated URL and place my custom name link below
htts://mydomainname/filename
What modifications i need to do for below code
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
Not sure exactly where this code lives for you, but here is a solution using XmlHttpRequest "onload".
oReq.onload = function(e) {
if (this.status === 200) {
const blob = new Blob([oReq.response], { type: "image/pdf"})
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myFile.pdf'; // gives it a name via an a tag
a.click();
window.URL.revokeObjectURL(url);
} else {
// handler error eee
}
}
Basically rather than $window.open(fileURL); you need to programmatically create a anchor tag, setting its href with the window.URL.createObjectURL as youve done above.
Hope this helps,
Matt

Not able to Download ICS file in safari browser

I am trying to download ICS file in all the browsers.
I am able to download ICS file in chrome but not in safari. Here is the javascript code that i used.
if(isChrome)
{
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=fileName+".ics";
link.click()
}
if(!isChrome)
{
` alert("not chrome");
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + escape(data));
var fileName = fileName+'.ics';
downloadLink.setAttribute('download', fileName);
var clk = document.createEvent("MouseEvent");
clk.initEvent("click", true, true);
downloadLink.dispatchEvent(clk);
document.body.appendChild(downloadLink);
downloadLink.dispatchEvent(clk);
//download(data, fileName+".ics", "text/calendar");
}
In Safari browser the generated file is getting downloaded but that file name is not getting appended. The filename i am getting is "Unknown" but the size of the file is 3KB and the content is there only the filename and extension is not getting added to the file.
Please let me know how i can solve this issue.
Thanks in advance
You should specify blob type. { type: 'text/calendar' }
const blob = new Blob([data], { type: 'text/calendar' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename + ".ics" ;
link.click();
Use this to download the file successfully, but you have to manually add it to the calendar. Safari does not include ics in a list of safe files and it will not be opened automatically.
If the problem is that you're using safari 10.1 or below the problem might be that it doesn't like the download attr.
http://caniuse.com/#feat=download

Download file when clicking on the link in Meteor

I store the mp3 files on my server using https://github.com/CollectionFS/Meteor-CollectionFS. I want to allow user to download the file just by clicking on the link and the 'download' attribute should work fine here i.e.:
download
The problem is that the file is opening/playing in the browser instead of just start to downloading to disk.
As discussed here https://code.google.com/p/chromium/issues/detail?id=373182 I guest it is because of cross origin request, so I tried to follow the suggested solution and use this link
download
with this handler
Template.podcastItemSummary.events({
'click a.btn-download': function(event, instance){
event.preventDefault();
downloadFile($(event.currentTarget).attr('data-url'));
}
});
if (Meteor.isClient) {
downloadFile = function(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:"audio/mp3"});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = sUrl.split('/').pop();
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
};
xhr.send();
}
}
Now the file is downloaded as expected, but for large files there is a strange delay between 'click' and start of download. Any better solution?
As #ZuzEL wrote, the solution is to just end the link with ?download
download
I stored the url in a separate collection, and now I realized that I should store only the file's id (ubcq5Xev4mkQ3sv5t) as there is a by design solution https://github.com/CollectionFS/Meteor-CollectionFS/wiki/How-to:-Provide-a-download-button
Template.fileList.helpers({
files: function () {
return Files.find();
}
});
and template
<template name="fileList">
<div class="fileList">
{{#each files}}
<div class="file">
<strong>{{this.name}}</strong> Download
</div>
{{/each}}
</div>
</template>
which produces an url that includes a token as well
Download

blob not downloading in safari

i'm trying to download a csv file, however it seem to work in all browsers except safari? how come is that. in safari it is just showing it in the browser?
Here is my code:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "text/csv;charset=utf-8"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
setTimeout(function(){
window.URL.revokeObjectURL(url);
}, 100);
};
}());
Your using the HTML 5 download attribute on the anchor tag which Safari doesn't support.
http://caniuse.com/#feat=download
It's probably best to link to the file and set headers like so to tell the agent to download rather than display.
Content-Type: text/csv
Content-Disposition: attachment; filename="whatever.csv"

Categories