Download With Current User Time As Filename
12,652
You can do this most simply with the onclick
attribute.
<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf" onclick="this.download='pizza-' + getFormattedTime() + '.pdf'">Click here</a>
Or, if you want to use Jquery:
In HTML (adding an id so we can select):
<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf" id="download">Click here</a>
In JS:
$("#download").click(function() {
this.download= 'pizza-' + getFormattedTime() + '.pdf'
}
Now, when the user clicks the link, the download name will be changed immediately to the current time.
Here's an example for how to get the time (heavily based on this answer):
function getFormattedTime() {
var today = new Date();
var y = today.getFullYear();
// JavaScript months are 0-based.
var m = today.getMonth() + 1;
var d = today.getDate();
var h = today.getHours();
var mi = today.getMinutes();
var s = today.getSeconds();
return y + "-" + m + "-" + d + "-" + h + "-" + mi + "-" + s;
}
Comments
-
Dani almost 2 years
In short
How can I make a file's name contain the user's local time upon downloading it?
Example:<a href="/pizza.pdf" download="pizza-CURRENT-USER-TIME-HERE.pdf">Click here</a>
In long
- I know I can give it the server's local time with PHP, as mentioned here:
How to get the current date and time in PHP? - I know I can print the user's local time to the screen, with JavaScript, as mentioned here:
How to show current time in JavaScript in the format HH:MM:SS?
What about the download having the user's time in the name?
With PHP, I know I can
echo
a variable into the file's name, like this:PHP:
date_default_timezone_set('America/New_York'); $current_date = date('Y-F-j-h-i-s');
HTML:
<a href="/pizza.pdf" download="pizza-<?php echo $current_date; ?>.pdf">Click here</a>
Or, with JavaScript, I can print the user's local time in the link (or anywhere on the screen).
How can I get the user's local time as the value for the download attribute?
I'm open to using PHP, JS, JQuery, etc.
- I know I can give it the server's local time with PHP, as mentioned here: