how to make a button download a python file in html? - javascript

I've tried several ways such as:
<button class="btn" type="submit" onclick="window.open('client.py')"><i class="fa fa-download"></i> Download</button>
or
<a href="/D:/Website/client.py" download>
python file
</a>
or
<a href="#" data-href='https://i.imgur.com/Mc12OXx.png' download="Image.jpg" onclick='forceDownload(this)'>Download Image</a>
js part:
function forceDownload(link){
var url = link.getAttribute("data-href");
var fileName = link.getAttribute("download");
link.innerText = "Working...";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
link.innerText="Download Image";
}
xhr.send();
}
but all of them seem to open the python file in a new window. and that new window/tab, just displays the file's code on the screen...
I however, want the file to be downloaded on the computer, not opened in another window!
*The last code that I referenced didn't work at all, I'm not sure why, also it's a bad example because I was trying to use that code to download a picture and not a python file, but you get the idea, in addition, I struggle understanding the code, since it uses js and js is a language I have very little knowledge in.
could anyone help?

You can use this for the button
<form method="get" action="client.py">
<button type="submit">Download!</button>
</form>

Related

Is there any way to make this download button to work using https link?

I am trying to download something from another website, I have tried this but didn't work. Please I need a help here
<a href="https://www.samanthaming.com/logo.png" class="text-1 text-uppercase" download> download here</a>
At first, make sure the download link is valid. Now You can make a custom javascript function to force download from an external link.
<script>
function downloadForce(link){
var url = link.getAttribute("data-href");
var fileName = link.getAttribute("download");
link.innerText = "Downloading...";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
link.innerText="download here";
}
xhr.send();
}
</script>
<a class="text-1 text-uppercase" href="#" data-href='https://i.imgur.com/U2KQsBD.jpeg' download="image.jpeg" onclick='downloadForce(this)'>download here</a>

Creating a file and triggering download in Javascript

I've got a really simple line in my code that should trigger the download of a file created on the go.
window.open(window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"})));
But for some reason, this does not work. A new window starts appearing, and then suddenly disappears.
Any clue why this doesn't work?
EDIT: If I call
`window.location = window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"}));`
It opens the file. But nothing was downloaded.
Try this solution
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
return function () {
var data = "Your data...........",
fileName = "filename";
blob = new Blob(data, {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.text = "download file";
window.URL.revokeObjectURL(url);
};
}());
this will create new <a> element. You can download the file by clicking it.
This needs HTML 5 support and for more options, check answers for this question.

How to download PDF automatically using js?

My scenario is that PDF file download automatically, then user fills it and when click on submit button in PDF it connect to java servlet and save it in DB.
User click on Button
JavaScript code run and PDF file download automatically
open file using JavaScript automatically
user fills & press submit
after submit servlet code run and save data in db
In my Application just the 2nd point is missing. Please provide code how to interact with extension using JavaScript to download file automatically.
I just want to download the file.
Use the download attribute.
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
save.download = fileName || filename;
if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
document.location = save.href;
// window event not working here
}else{
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
How to use?
download_file(fileURL, fileName); //call function
Please try this
(function ($) {
$(document).ready(function(){
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if($('.submitclass').length){
$('.submitclass').click(function(){
$email_id = $('.custom-email-field').val();
if (validateEmail($email_id)) {
var url= $(this).attr('pdf_url');
var link = document.createElement('a');
link.href = url;
link.download = url.split("/").pop();
link.dispatchEvent(new MouseEvent('click'));
}
});
}
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<div class="form-item form-type-textfield form-item-email-id form-group">
<input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
</div>
<button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
Or use download attribute to tag in HTML5
for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf
e.g. you're using php and $filepath contains pdf file path.
so you can write javascript like to to emulate download dialog box.
<script language="javascript">
window.location.href = '<?php echo $filepath; ?>';
</script
Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

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

How can I know when the file download/"Save As" prompt appears?

I have a link on a page
<a class="btn btn-success" href="DownloadCsv">Download CSV</a>
When the user clicks on said link, the server responds with the header Content-Disposition: attachment to prompt the user with the "Save File" Dialog.
What I'd like to accomplish is: disable the link while the server is generating its response, and enable it once the server responds.
Is there any event fired for that response from the server? Or is there any other way to accomplish this?
The only way that comes to my mind is using AJAX.
You first download it with AJAX where you have events that guide you (like ready state etc.).
Then you do the actual download, but at that point it is served from the browsers cache.
So it is not actually downloaded but instantly loaded from disk.
The user will not tell the difference but you will be able to detect the end of the actual download.
I went through my old questions. I even don't remember what I need it for but I decided to answer on this now because it has not been solved yet after 3.5 years... It can be accomplished this way
Link can be
<a class="btn btn-success" onclick="clickHandler(this); return false;">Download CSV</a>
Handler
function clickHandler(element) {
//disable link
var href = element.href;
element.href = 'javascript:void(0)';
//download file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'DownloadCsv', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) { binaryString[i] = String.fromCharCode(uInt8Array[i]); }
var data = binaryString.join('');
//initiate save as dialog
var base64 = window.btoa(data);
var a = document.createElement('a');
a.href = 'data:application/csv;base64,'+ base64;
a.setAttribute('download', 'data.csv');
a.click();
//enable link
element.href = href;
}
};
xhr.send();
}

Categories