Force <a download /> to download image instead of opening url link to image [duplicate] - html

This question already has answers here:
How can I create download link in HTML?
(12 answers)
Closed 1 year ago.
<a download='file' href="https://tinyjpg.com/images/social/website.jpg">
Download
</a>
Is there a way to force the download of a file instead of opening the file in a new window? Right now if the file is a URL, like the example below it won't be downloaded and will open in a new window.

You may be bitten by the fact that Firefox and Chrome 65+ only support same-origin download links, probably as a security measure.
Source: https://caniuse.com/#feat=download (see "Known issues" tab)
The Web Hypertext Application Technology Working Group (WHATWG) recommends that in cross-origin scenarios (as in your example), the web server that is hosting the image/file in question needs to send a Content-Disposition HTTP header for download= to be honored.
Source: https://html.spec.whatwg.org/multipage/links.html#downloading-resources
In short:
You can only use <a download='...'></a> to force download of an image/file, if:
the html and the image/file are hosted on the same domain,or
the image/file is on a different domain, and that server also says it should be downloaded.

Maybe you have solved in the meanwhile, but since you are hosting the files on S3 (see comments on Peter B's answer), you need to add a signature to the files url and set the ResponseContentType to binary/octet-stream by using the aws sdk. I am using Node so it becomes:
const promises = array.map((item) => {
const promise = s3.getSignedUrlPromise('getObject', {
Bucket: process.env.S3_BUCKET,
Key: key, //filename
Expires: 604800, //time to expire in seconds (optional)
ResponseContentType: 'binary/octet-stream'
});
return promise;
});
const links = await Promise.all(promises);
I hope this helps.

setTimeout(function() {
url = 'https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png';
// downloadFile(url); // UNCOMMENT THIS LINE TO MAKE IT WORK
}, 2000);
// Source: http://pixelscommander.com/en/javascript/javascript-file-download-ignore-content-type/
window.downloadFile = function (sUrl) {
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
//alert('Your device does not support files downloading. Please try again in desktop browser.');
window.open(sUrl, '_blank');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
link.setAttribute('target','_blank');
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
if (sUrl.indexOf('?') === -1) {
sUrl += '?download';
}
window.open(sUrl, '_blank');
return true;
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

You can use this function to downlaod images using fetch
async function downloadImage(imageSrc) {
const image = await fetch(imageSrc)
const imageBlog = await image.blob()
const imageURL = URL.createObjectURL(imageBlog)
const link = document.createElement('a')
link.href = imageURL
link.download = 'image file name here'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}

Your link should have an ID to force download:
<a download='website.jpg' id='blablabla' href="https://tinyjpg.com/images/social/website.jpg">
Download
</a>

Related

Display a pdf file in the browser with sails

I have some documents in a directory and I want to show one embedded in the browser, I save the path of the document in a table and I can read the path from that table and download the document, but I can't figure out how to show the file in the browser.
I'm using the following code to send the file:
loadDocument: async function (req,res){
var SkipperDisk = require('skipper-disk');
var fileAdapter = SkipperDisk(/* optional opts */);
var fd = await Documents.find(
{
where: {id:'1'},
select: ['uploadFileFd']
}
).limit(1);
let uploadFileFd = fd[0]["uploadFileFd"];
var fileStream = fileAdapter.read(uploadFileFd);
fileStream.on('error', function (err){
return res.serverError(err);
});
res.contentType("application/pdf");
res.set("Content-disposition", "attachment; filename=" + "file"+ fd[0]["id"]+".pdf");
fileStream.pipe(res);
},
I want to call the function and load the pdf file in the browser, preferably without reloading all the page.
Clients browsers will download the pdf without trying to open the built-in PDF viewer (ie, Chrome) because of the Content-disposition: attachment header that you're sending - try using inline instead.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
res.setHeader('Content-type', 'application/pdf');
res.setHeader('Content-disposition', 'inline; filename="file' + fd[0]["id"] + '.pdf"');
I found a solution to my problem.
First I have to create a way to serve the static folder where the files are located, I found the answer here.
Then I modify the code to send the data encoded as base64 using 'base64-stream':
var readStream = fs.createReadStream(uploadFileFd);
readStream.on('open', function () {
readStream.pipe(new Base64Encode()).pipe(res);
});
readStream.on('error', function(err) {
res.end(err);
});
Finally I show the pdf file in the browser as follows:
.done(function(data){
var parent = $('embed#pdf').parent();
var newElement = "<embed src=data:application/pdf;base64,"+data+" id='pdf' width='100%' height='1200'>";
$('embed#pdf').remove();
parent.append(newElement);
})
Now I can display a pdf file in the browser embedded in my own page, thanks to all the people that try to help.

chrome PDF viewer can't download file

Here is my situation, I got a server running a PDF generator, when I make a request with some params, it will give me back a PDF file, the PDF is not stored in the server it's generated during the runtime.
Everything goes fine, I can get the PDF open in chrome's PDF viewer, but if want to download the file, an error occurred, like the image shows.
Because Chrome go to the origin URL to request the file, but the file is not a static resource on the server.
I don't know if anybody has run into this problem?
Whenever you leave the website you used to create the object URL (window.URL.createObjectURL(...)) that very object will get garbage collected. So you need to keep a reference to that object somehow.
This works for us in Chrome, Firefox, Safari, iOS Safari & Android to first display the PDF in capable browsers in a new tab and allow a download afterwards (in IE it just starts the download):
function openPdfInNewTab(url,
postData,
description = 'Document',
filename = description + '.pdf') {
if (!window.navigator.msSaveOrOpenBlob) {
var tabWindow = window.open('', '_blank');
var a = tabWindow.document.createElement('a');
a.textContent = 'Loading ' + description + '..';
tabWindow.document.body.appendChild(a);
tabWindow.document.body.style.cursor = 'wait';
} else {
spinnerService.show('html5spinner');
}
$http.post(url, postData, {responseType: 'arraybuffer'})
.then(function showDocument(response) {
var file = new Blob([response.data], {type: 'application/pdf'});
if (window.navigator.msSaveOrOpenBlob) {
spinnerService.hide('html5spinner');
window.navigator.msSaveOrOpenBlob(file, filename);
} else {
tabWindow.document.body.style.cursor = 'auto';
var url = a.href = window.URL.createObjectURL(file);
a.click();
a.download = filename;
}
$timeout(function revokeUrl() {
window.URL.revokeObjectURL(url);
}, 3600000);
}, handleDownloadError);
}
We have been opening PDFs in a new browser-tab and had similar issues.
For us it started working again when we use window.URL.createObjectURL instead of tabWindow.URL.createObject which displayed the PDF but didn't allow the download.
Chrome's built in PDF viewer will download the pdf file through the PDF's origin URL. So if the PDF is generated at server runtime and if it's not stored in the sever, the download could fail.
see link here: https://productforums.google.com/forum/#!topic/chrome/YxyVToLN8ho
Just as an additional comment:
We had the same problem on a project, on Chrome only.
Authenticated GET request would fetch the PDF as an attachment from API, and we would forward it via window.createObjectURL(blob) to the browser viewer.
The Network Error was due us invoking window.revokeObjectURL(url); after opening the PDF. When we removed that line, the blob wasn't garbage collected immediately after opening.
fetch(request)
.then(async response => {
if (!response.ok) {
return reject(response.statusText);
}
const blob = await response.blob();
const url = await window.URL.createObjectURL(blob);
window.open(url, '_blank');
URL.revokeObjectURL(url); // This line was causing the problem
resolve();
})
.catch(reject)

HTML <a> tag download file error handling

In my app I have tag with link to api for file download (pdf). The problem is that it is not 100% stable and I have to handle then service is not available or file is not available and server responds with error.
<a href="link/to/api" target="_blank" download="filename">
By the way I am using AngularJS in this app. If there is any solution using it it would help a lot
In case somebody else will face similar problem. Here is the solution I have implemented after some research.
Remove the link from an <a> tag and add a click event:
<a href="#" ng-click="downloadFile()">
now you need to download blob (here you can control if you can access it file) and let make DOM object add all needed attributes end trigger it.
$scope.downloadFile = function () {
$http.get('api/link', { responseType: 'arraybuffer' })
.then(function (data) {
var file = new Blob([data], { type: "application/pdf" });
var url = $window.URL || $window.webkitURL;
var fileURL = url.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "nameOfFile";
a.target = "_self";
a.click();
url.revokeObjectURL(fileURL);
}).error(function (data) {
console.error(data);
})
};
UPDATE:
This was working only for Chrome. Other browsers had different approach of downloading blob. So I have users FileSaver.js for this task. Even then I had problems opening it on iOS. It is blocking file saving if it was triggered out side of user event. Here is my workaround for this.
var file = new Blob([data], { type: "application/pdf" });
var isIos = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
if(isIos){
var element = document.getElementById("downloadButton");
element.onclick - function(){
saveAs(file, "name.pdf");
}
element.onclick();
} else {
saveAs(file, "name.pdf");
}
Hope this will save time for someone.
Use extensionnames after the link like link/to/api.pdf and download="filename.pdf".
Also, try target="_self"

How would I read the file contents of a file in my app/extension's crx?

I want to include some files in my crx and then be able to read them in as data (into a string or Blob). How would I do this? Is there a way to use the FileSystem API for this?
chrome.runtime.getPackageDirectoryEntry was implemented on 2013-06-13, expected in Chrome 29:
Issue 177208: add read-only FileSystem API for access to packaged app/extension resources
Change: https://chromiumcodereview.appspot.com/16470003
Read file contents from crx via XHR is much more simple than FileSystem API:
var url = chrome.extension.getURL('the_file.txt'); // full url
var req = new XMLHttpRequest(); // read via XHR
req.open('GET', url);
req.onreadystatechange = function(e) {
if (req.readyState === 4 && req.status === 200) {
console.log(data);
} else {
// error
}
}
If you want to make the request in an injected context, you must have accessable resources declared in manifest.json first, list filename (support wildcards) in accessible resources entry.
"web_accessible_resources": [
"path_to_the_file.html",
"just_another_folder/*.txt"
]

Filename of downloaded file in data:Application/octet-stream;

I am trying to download a file using data uri in following manner:
<input type="button"
onclick="window.location.href='data:Application/octet-stream;content-disposition:attachment;filename=file.txt,${details}'"
value="Download"/>
The problem is that the downloaded file is always named 'Unknown', whatever I try to use as
filename. Is this the correct way to give the file a name ? or something else needs to be
done ?
Here's the solution, you just have to add a download attribute to anchor tag
a with desired name
<a href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"
download="somedata.csv">Example</a>
Another solution is to use JQuery/Javascript
Anchor's Download Property
On Safari, you might want to use this, and instruct the user to ⌘-S the file:
window.open('data:text/csv;base64,' + encodeURI($window.btoa(content)));
Otherwise, this uses Filesaver.js, but works ok:
var downloadFile = function downloadFile(content, filename) {
var supportsDownloadAttribute = 'download' in document.createElement('a');
if(supportsDownloadAttribute) {
var link = angular.element('<a/>');
link.attr({
href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(content)),
target: '_blank',
download: filename
})[0].click();
$timeout(function() {
link.remove();
}, 50);
} else if(typeof safari !== 'undefined') {
window.open('data:attachment/csv;charset=utf-8,' + encodeURI(content));
} else {
var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename);
}
}
Note: There is some AngularJS in the code above, but it should be easy to factor out...
I had the same issue and finally I solved in all browsers serving the CSV file in the server-side:
const result = json2csv({ data });
res.writeHead(200
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment;filename=issues.csv',
'Content-Length': result.length
});
res.end(result);
For those that are using other libraries like angularjs or backbone, you can try something like this.
$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+$scope.data);
For anybody looking for a client-side solution using Javascript only, here is mine, working on any browser except IE 10 and lower (and Edge...why?!):
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);
var link = document.createElement('a');
link.setAttribute("download", "extract.csv");
link.setAttribute("href", uri);
document.body.appendChild(link);
link.click();
body.removeChild(body.lastChild);