*Hi … I want to be able to use a link to download a remote file(media) that is created on the server side (with uplink) and it returns a link address. I want to use that link address in a Link component to download that remote file to the user.
So the server side creates a media file an saves it in an nginx accessible folder and then returns the web address … ie., https://mysite.com/the_media_file. I would like to be able to use that address in a link to download the file. Worse case, perhaps I could put the html for a link in a Blob media object and have it displayed when the link is clicked but seems that is a not as easy and creates a messy url – can we add a ‘download’ attribute to a link. Perhaps I can do that in javascript but again is there a correct way to do that ?
Okay … I will answer my own question. Yes it possible to have javascript modify the link to add “download” attribute and you could remove the target=‘_blank’ attribute. But the browsers do not want to download cross site files so it mostly will not work. Code I used for this is below - works perfectly.
But the final solution is to add headers to the server (I am using Nginx) to force the download… For example in case your download files are in the directory media –
location /media {
add_header Content-disposition “attachment; filename=$1”;
default_type application/octet-stream;
}
For purposes of adding attributes to the Link <a tag you can use something like:
type or paste code here<script>
try {
console.log('Simple link modification script starting');
function fixDownloads() {
console.log('Checking for download links');
var links = document.getElementsByTagName('a');
var fixed = 0;
for (var i = 0; i < links.length; i++) {
var link = links[i];
var href = link.href || '';
var text = link.textContent || '';
if (href.indexOf('YOUR site domain or IP') > -1 &&
(href.indexOf('.mp4') > -1 || href.indexOf('text in your link..like download me') > -1)) {
if (!link.hasAttribute('download')) {
link.setAttribute('download', '');
link.removeAttribute('target');
console.log('Fixed download link: ' + text);
fixed++;
}
}
}
if (fixed > 0) {
console.log('Fixed ' + fixed + ' download links');
}
}
// Run multiple times to catch the finished page as it is dynamic in my waiting // for the link to become available
setTimeout(fixDownloads, 1000);
setTimeout(fixDownloads, 3000);
setTimeout(fixDownloads, 5000);
setTimeout(fixDownloads, 10000);
// Make it available globally
window.fixDownloads = fixDownloads;
} catch (e) {
console.error('Download script error:', e);
}
</script>